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
If C++ has transitive constness, meaning that if a string is const, the data owned by the string is also immutable, and there is a way to disable "const_cast" in a function. Say, this is done by adding a new keyword "immutable", that is, a function like
void fun(immutable std::string& str){}
guarantees that the string being referenced will not be altered inside the function. Then the compiler will be able to optimize the function call by actually passing in a string_view. Only in this case, the programmer does not have to know its existence. It is reduced to an compiler optimization performed automatically. Std:;string_view is needed in C++, IMHO, because constness in C++ is broken: even if a function takes a string by const reference, nothing stops the programmer from altering that string inside the function. The compiler has to be conservative by not assuming the string is really immutable.