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.
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.
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 ""
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With