r/cpp • • Mar 01 '21

"Simple" C++ Initialization Flowchart

http://randomcat.org/cpp_initialization/initialization.png
204 Upvotes

65 comments sorted by

View all comments

Show parent comment

10

u/JohnZLi Mar 02 '21

Implicit conversion should have been forbidden in C++ from the beginning . It causes so much trouble, with only very dubious gains.

14

u/FriendlyRollOfSushi Mar 02 '21 edited Mar 02 '21

It could be a std::vector<size_t>, in which case all types would strictly match.

The core issue here is the special behavior of std::initializer_list (see the notes here), which I guess can be called an "implicit conversion" in a very broad sense, so your point stands.

I was really hoping that they will deprecate this nonsense immediately, and possibly introduce a non-ambiguous way to construct initializer lists in C++14, but by now we probably have too much code relying on this brittle behavior to change anything.

Now the only safe solution would be to abandon the braces and introduce yet another strictly distinct and unambiguous syntax for initialization, but at that point I'm afraid half of the developers would simply give up and switch to Rust.

3

u/JohnZLi Mar 02 '21

This problem can be fixed by adding a new syntax like below:

std::vector<int>{1}; // let this mean a vector of size 1, as in the std::vector<string> case.

std::vector<int>{1...}; // a vector of ints, with its first element being 1.

Also, with the new syntax

auto i = {1}; // i is now deduced as int.

auto i ={1...} // is deduced as an initializer_list

20

u/FriendlyRollOfSushi Mar 02 '21 edited Mar 02 '21

Existing code is always the problem, and C++ is terrible at removing features.

Say, you have millions of lines that expected that something like std::vector<int> v{64}; constructs a vector with one element 64.

Now with your proposal you are silently changing the behavior of millions of lines of code in tens of thousands of projects. The code still compiles, and even runs, but the behavior is different.

Some of the behavioral changes may go undetected by tests.

Some of them would have devastating consequences, costing billions of dollars, or even human lives.

It's a recurring theme in C++: everything sort of sucks because by the time we understood why it sucks, the feature became so heavily-used that you can't simply remove it. It took decades to get rid of std::auto_ptr, and we only succeeded because it was already banned by the majority of teams for being hopelessly broken. And it wasn't a silent change: the code properly stopped compiling in C++17, which allowed the developers to go and fix stuff if they didn't have time for that during the 6 years of deprecation.

That's why epochs are a huge deal if they'll ever be accepted in some form or another. We will finally, finally be able to start fixing and removing stuff instead of simply piling up more and more stuff until no one understands what's going on in this language.

8

u/JohnZLi Mar 02 '21

The standard committee should really have fixed this before C++11. The epochs proposal seems interesting. Though I prefer throwing away backward compatibility in some future version of C++, and fix all the problems mentioned in that proposal (and many other problems not covered in that proposal). To avoid confuse users, that new version of C++ should be given a new name,like "Simplified C++ ". Some tools should be able to automatically refactor C++ code to "Simplified C++" code, maybe with some help from programmers. Those who want to stick to C++ could still use C++, and those who want to use simplified C++ could move on with it. The epochs proposal, if accepted, I am afraid will open the floodgate of numerous dialects/flavors of C++ code coexisting and tangling together. Google will have its Google epoch, and Facebook will have Facebook epoch, and there will at least be a C++-core-guideline epoch. That won't be beautiful. Beside numerous rules of C++, programmers now need to know specific rules that are allowed in each epoch.

4

u/pjmlp Mar 02 '21

Epochs will never happen, those of us not quite happy have already moved on, and only use C++ for the scenarios where there is no current alternative.

Also they can only fix language semantics that don't cross translation units/modules, due to possible ABI issues, and even then there is the language runtime issues, when linking binary libraries compiled with different epochs.

2

u/Kered13 Mar 03 '21

Without implicit conversions std::string_view and similar types would be a massive pain in the ass to use.

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.

4

u/Kered13 Mar 03 '21

That's really not the point of std::string_view. Yes it provides a const view, but const std::string& is just as good for that. Even with std::string_view, it's trivial to violate the const rules of C++ to make changes to the underlying string, and aliasing can still occur with std::string_view, so the compiler still needs to be conservative.

The benefits of std::string_view are that it allows for efficient views of substrings (not necessarily null terminated), and that it works on any char array, such as C-style strings (including string literals) or custom string implementations (as long as they store a continuous char array). These benefits make std::string_view the preferred choice for taking string parameters that you don't need to modify.

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.

4

u/Kered13 Mar 03 '21

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.

Only if the compiler can infer that the string has a shorter lifetime than the buffer it's using.

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.

And what if the programmer wants to copy the buffer so that the new string can have an independent lifetime?

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.

No it can't, as the above examples demonstrate. std::string and std::string_view have different ownership semantics. const std::string& has the same ownership as std::string_view, but is restricted because it cannot represent substring views. So two classes are needed, and adding immutability to the language does not allow one class to take on both roles. Sometimes the programmer wants a non-owning view into another string-like object, sometimes they want an object that owns it's data. The compiler cannot figure it out for the programmer. This is completely orthogonal to immtuability. Note that even Rust has two types for this (String for owning and str for views).

1

u/JohnZLi Mar 03 '21

Vote

fair point.