问题
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