Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad to depend on index 0 of an empty std::string?

Tags:

c++

stdstring

std::string my_string = ""; char test = my_string[0]; 

I've noticed that this doesn't crash, and every time I've tested it, test is 0.

Can I depend on it always being 0? or is it arbitrary?

Is this bad programming?

Edit: From some comments, I gather that there is some misunderstanding about the usefulness of this.

The purpose of this is NOT to check to see if the string is empty. It is to not need to check whether the string is empty.

The situation is that there is a string that may or may not be empty. I only care about the first character of this string (if it is not empty).

It seems to me, it would be less efficient to check to see if the string is empty, and then, if it isn't empty, look at the first character.

if (! my_string.empty())     test = my_string[0]; else     test = 0; 

Instead, I can just look at the first character without needing to check to see if the string is empty.

test = my_string[0]; 
like image 415
beauxq Avatar asked Oct 12 '15 14:10

beauxq


People also ask

Can std :: string be empty?

std::string::emptyReturns whether the string is empty (i.e. whether its length is 0). This function does not modify the value of the string in any way.

Is an empty string 0?

The empty string is the special case where the sequence has length zero, so there are no symbols in the string.

Is std :: string empty by default?

The closest you can get is to check whether the string is empty or not, using the std::string::empty method.. The default construction of std::string is not "" ; it is {} . Default-constructing avoids having to check the char const* , find it is an empty string, and eventually do nothing.

What does an empty string contain in C++?

The empty string is a substring of the empty string, and so is contained in that sense. On the other hand, if you consider a string as a collection of characters, the empty string can't contain the empty string, because its elements are characters, not strings.


1 Answers

C++14

No; you can depend on it.

In 21.4.5.2 (or [string.access]) we can find:

Returns: *(begin() + pos) if pos < size(). Otherwise, returns a reference to an object of type charT with value charT(), where modifying the object leads to undefined behavior.

In other words, when pos == size() (which is true when both are 0), the operator will return a reference to a default-constructed character type which you are forbidden to modify.

It is not special-cased for the empty (or 0-sized) strings and works the same for every length.


C++03

And most certainly C++98 as well.

It depends.

Here's 21.3.4.1 from the official ISO/IEC 14882:

Returns: If pos < size(), returns data()[pos]. Otherwise, if pos == size(), the const version returns charT(). Otherwise, the behavior is undefined.

like image 78
Bartek Banachewicz Avatar answered Sep 20 '22 01:09

Bartek Banachewicz