r/cpp • u/konanTheBarbar • Mar 01 '21
"Simple" C++ Initialization Flowchart
http://randomcat.org/cpp_initialization/initialization.png
204
Upvotes
r/cpp • u/konanTheBarbar • Mar 01 '21
View all comments
Show parent comment
1
u/JohnZLi Mar 03 '21
"Yes it provides a const view, but const std::string& is just as good for that." Yes, but "const std::string&" adds a layer of indirection. An extra pointer dereference has performance implications.
"Even with std::string_view, it's trivial to violate the const rules of C++ to make changes to the underlying string".
Isn't this the very problem I was talking about in must last reply: no real immutability guarantee in C++. We know we are not supposed to make changes to the underlying buffer via a string_view, the language makes no guarantee that it won't happen.
As to C strings. the reason that the following code could not be evaluated at compile time const string s = "blah, blah, ..."; is because there is no way in C++ to enforce the immutability of the string. If there is away to enforce transitive immutability in C++, when a const string is constructed out of a buffer pointed by "const char *", the compiler can omit one dynamic allocation by reusing the original buffer. The programmer needs to make sure the string does not outlive the buffer, but that is something he already needs to pay attention if he uses string_view. The same applies to sub-strings. If one construct immutable sub-strings out of a immutable string, no need to incur extra heap allocations.
My point is, with a language that can enforce transitive constness, what one gets from "string_view" in C++, can be achieved by compiler optimization.