How to initialize std :: string using ""?

I have to deal with the problems of initializing the variable std :: string using "" (i.e. an empty string). This causes strange behavior in code that previously worked. Is the following statement wrong?

 std::string operationalReason = ""; 

When I use the following code, everything works fine:

 std::string operationalReason; operationalReason.clear(); 

I believe that string literals are stored in a separate memory cell, depending on the compiler. Can the problem that I see really indicate damage to this repository? If so, it will be hidden by using the clear() function.

Thanks.

+8
c ++ stdstring
source share
4 answers

What happens if you just do std::string operationalReason; ? This should have the same effect as the two examples you cited. If you are actually having problems using the form std::string operationalReason = ""; , which may indicate damage to the string data store, but it may also mean that some OTHER parts of the memory are corrupted, and this particular line causes it to appear differently.

Does the code crash immediately after using the form "" or later at runtime? Can you run this under valgrind or similar to see if there are memory problems? What happens if you initialize a string to some literal other than "" ?

+4
source share
 std::string operationalReason; //is enough! 

It calls the default constructor and still creates an empty string.

So, I would say that std::string operationalReason = "" is redundant.

+24
source share

std::string operationalReason = "";

It's fine, technically, but more common and nice just

std::string operationalReason;

By default, ctor lines will create an empty line

Yes, you are correct that string literals are stored in immutable memory blah blah, etc. etc., but the copy-ctor string always copies the string or C-string passed

+10
source share

Two forms are fixed, but this one:

 std::string operationalReason = "" 

It calls the constructor, which takes a const char * argument. First, it calls the default constructor, and then tries to copy the data, in this case nothing.

 std::string operationalReason; 

is preferred. You can use clear() to reset for an empty string.

-4
source share

All Articles