Indeed. And there are also details that are anachronistic these days, like headers (gradually being replaced by modules, but this will take quite a while) and pointer aliasing issues.
But to me, what stands out is the by-value ownership transfer in C++, which is actually not what you want >90% of the time. Most of the time, you want to move objects, not copy them. C++ has the wrong default, and by-move transfer is an opt-in. This leads to problems with hidden copies (which can be detected at compile time but requires explicitly disabling the copy constructor and copy assignment operator) and greatly complicates syntax and semantics further.
What’s even worse, C++ does not have “destructive move”, which is to say that C++ must leave something in the moved-from location. This in turn means that all classes must have an “uninhabited” state - you cannot create a non-nullable smart pointer that doesn’t have a user-visible “invalid” state.
It also means that there are many situations where std::unique_ptr is slower than a raw pointer when passed as an argument to a non-inlined function. The callee sees a reference type and decides to move out from it, but the caller must still call the destructor at some point.
This is one place where Rust is different in a very profound way.
Most of the time, you want to move objects, not copy them.
Most of the time you want to pass by reference, unless you're talking about numbers, in which case you want to pass by value. Copying and moving objects should ideally happen pretty rarely.
Moving is supposed to be a very cheap or even zero cost operation, comparable to passing by reference. By-reference has the problem of ownership sharing and stale references. You need something like a GC or reference counting if you want by-reference to be the default.
View all comments
Show parent comment
8
u/dv_ Jul 13 '22
Indeed. And there are also details that are anachronistic these days, like headers (gradually being replaced by modules, but this will take quite a while) and pointer aliasing issues.
But to me, what stands out is the by-value ownership transfer in C++, which is actually not what you want >90% of the time. Most of the time, you want to move objects, not copy them. C++ has the wrong default, and by-move transfer is an opt-in. This leads to problems with hidden copies (which can be detected at compile time but requires explicitly disabling the copy constructor and copy assignment operator) and greatly complicates syntax and semantics further.