Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an std::string using ""?

Tags:

c++

stdstring

I'm facing problems with initializing a std::string variable using "" (i.e. an empty string). It's causing strange behavior in code that was previously working. 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 location that is compiler-dependent. Could the problem I'm seeing actually be indicating a corruption of that storage? If so, it would get hidden by my usage of the clear() function.

Thanks.

like image 292
Mohsin Avatar asked Mar 18 '11 15:03

Mohsin


3 Answers

std::string operationalReason; //is enough!

It invokes the default constructor, and creates an empty string anyway.

So I would say std::string operationalReason = "" is overkill.

like image 108
Nawaz Avatar answered Sep 27 '22 20:09

Nawaz


What happens if you just do std::string operationalReason;? That should have the same effect as the two examples you provided. If in fact you're experiencing problems when you use the std::string operationalReason = ""; form that may indicate that the string data storage has been corrupted, but it may equally mean that some OTHER part of memory is corrupted and that particular line causes it to manifest differently.

Does your code crash immediately when you use the "" form or later on at runtime? Are you able to run this under valgrind or similar to see if it spots memory problems? What happens if you initialized the string to some literal other than ""?

like image 21
Mark B Avatar answered Sep 27 '22 19:09

Mark B


std::string operationalReason = "";

This is perfectly fine, technically, but more common and nice is just

std::string operationalReason;

The default ctor of the string will create an empty string

Yes, you are right about string literals being stored in a nonmutable memory blah blah etc etc... but the string copy-ctor always copies the string or C-string passed

like image 23
Armen Tsirunyan Avatar answered Sep 27 '22 20:09

Armen Tsirunyan