+ 7
Are C++ Strings Initialized to Empty during Initialization?
Coming from C, I've always had the phobia of using uninitialized variables. int a; printf("%d", a+1); // bad That said, I've heard from people that std::string is initialized to "" or just empty when declared. I've yet to find any section in the C++ standard which states that std::string is indeed initialized to an empty string on declaration. Can I safely do std::string a; a += "hello"; std::cout << a; without expecting any undefined behavior or garbage values? I've always been doing std::string a = ""; before trying to concatenate to newly declared strings.
7 Antworten
+ 5
I just found this. Is that what you've been looking for?
https://en.cppreference.com/w/cpp/language/default_initialization
+ 5
As a C++ dev, it's still always important to initialize all variables. Because the design philosophy of C++ is to have zero overhead, this typically means minimal or no initialization inside of container. However I would suggest using `const char*` over `std::string` in most cases as it's more akin to what you're used to and I feel `std::string` has some bloat that you may not want in your code. Or if you need something equivalent to `const std::string&` then I suggest using `std::string_view` as it does that for you and it's a great opportunity for performance gain and code readability : )
EDIT: However in the case of a lot of "containers" like `std::vector`, it has to initialize itself, in which case you don't need to worry about it. Though I like the auto pattern where: `auto ivec = std::vector<int>();` as it corrects this. The move constructor should be called and it should end up elided which is as efficient as the normal declaration
+ 4
FYI
From the C++ standard:
N4659 §24.3.2.2 [string.cons]
The default state of an std::string is:
"data() - a non-null pointer that is copyable and can have 0
added to it
size() - 0
capacity() - an unspecified value"
+ 4
Thanks HonFu. I somehow overlooked the part saying
"... class, calls default ctor, the value is "" (empty string) ... "
Apparently I also looked everywhere except for the most obvious place... 🤦
http://www.cplusplus.com/reference/string/string/string/
@Dennis Thanks for the quote too!
0
Gossa Nono, hello. :)
Please read this:
https://www.sololearn.com/discuss/1316935/?ref=app
0
string a=“\0”;
is good practice to initialize it as null or empty string
0
Yes they are. You shouldn't initialize a string as | std::string str = ""; |. Not only that it's nonsensical, but it also has a decent performance penalty even though it doesn't actually do anything.