23 points · by meetingcpp · 12y ago · 14 comments
No, this is just the destructive move problem for single ownership pointers. It's an use case for "swap" as a language primitive.
The real problem is that you just can't make single-ownership pointers work right in C++ via the template mechanism. I tried a few times, over a decade ago. (http://animats.com/papers/languages/index.html) It takes a more global look than you have down inside a template. You need language-level support.
Rust does this. It's not inherently hard. It's just extremely hard to retrofit to the C++ model. Look at the history of auto_ptr, and now unique_ptr in C++. The pain. The anguish. The decades of headaches. The unnecessary complexity. The pain.
But I am also spoiled by Niklaus Wirth legacy in language design and safe systems programming. As well as ML languages.
C++14 feels quite modern, and I enjoy playing with it on hobby projects where I have full control, but I don't miss those C++98 enterprise code bases.
In general I find the lack of destructive move isn't a serious problem -- designing variables so their 'default state' is very cheap to construct isn't usually a major cost.
File fh = File(fopen("file.txt"));
foo(std::move(fh));
Using fh after foo() would yield a compile error in Rust. It does not in C++.
An object should be accessible for reassigning a value after its move, as its often needed for algorithms, thats exactly why the C++ Standard mandates this. Move does really only make sense if the class holds a moveable allocation, such as a container, array etc., which makes copying expensive.
The same is true in Rust. A moved-from value can be reassigned, but cannot be used (compile enforced) until it is reassigned. :)
To Quote Eric Niebler: "I want you to fear r-value references, like one could fear god" (last year at Meeting C++)
[1]except things like forwarding in templates, but thats fairly easy.