Prevent moving of a unique_ptr C++11

女生的网名这么多〃 提交于 2020-01-04 13:42:21

问题


Is there any way to prevent a user to explicity take ownership of a unique pointer with

 std::move

?


回答1:


Make it const

The unique_ptr move constructor takes a non-const rvalue reference, so can't be called with a const object.

const unique_ptr<int> owner(new int);
// ...
unique_ptr<int> thief = std::move(owner);  // ERROR

This allows unique_ptr to be used like a boost::scoped_ptr




回答2:


By returning a std::unique_ptr, you have given up the control of the object. The new owner will either destroy it, or pass it to somebody else.

If you don't intend the user to release the object, then return a reference.

you have boost::scoped_ptr/const std::unique_ptr (see Jonathan's answer) which technically answers your question -- the caller releases, but cannot give away the resource -- but I fail to see a compelling example of why would you need this rather that std::unique_ptr or a reference



来源:https://stackoverflow.com/questions/15296881/prevent-moving-of-a-unique-ptr-c11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!