Le 30/05/2017 à 04:13, Emil Dotchevski via Boost a écrit :
On Mon, May 29, 2017 at 12:50 AM, Andrzej Krzemienski via Boost < boost@lists.boost.org> wrote:
Now, because I have a moved-from state, it weakens all my invariants. As you say, every function now has a precondition: either I put defensive if's everywhere, or expect the users to be putting them.
Indeed, and this is not a good thing. Consider that the int handle doesn't have move semantics, even though (in theory) it is possible to define some type with invalid "moved from" state, even in C.
When dealing with things like file handles or any other resourse it's best to use shared_ptr. This entire File class you wrote can be reduced to a function that returns shared_ptr<int const> that closes the file in a custom deleter. Things are even more straight-forward if you use FILE *, then it's just shared_ptr<FILE>.
Are you suggesting that one should use shared_ptrs instead of movable types? Are you saying that the design of a movable std::fstream is wrong?
Why is it better to use shared_ptr instead of move-only wrappers when dealing with (file) handles? Because handles are copyable types and (by design) they can be shared. I would say that it depends on the application, we need movable and shared handles. BTW, I don't know what (std| boost) Filesystem provides?
IMO unique_ptr is way overused and shared_ptr way underused. I know,
"Overhead!!", Not only overhed. also the fact that you are implying shared ownership semantics (possibly across threads), even though you have none.
Your argument is that if it is incorrect to have more than one thread have access to the object then shared_ptr is the wrong design choice. But it doesn't necessarily follow, because move-only semantics don't _prevent_ multiple threads from accessing the object.
Multi-threading and ownership are two different things. Vicente