What happens if I reset a std::shared_ptr to itself

微笑、不失礼 提交于 2019-12-05 10:09:17

The specification for that overload of reset is given in 20.7.2.2.4 shared_ptr modifiers [util.smartptr.shared.mod], paragraph 3 (from n3290):

template<class Y> void reset(Y* p);

Effects: Equivalent to shared_ptr(p).swap(*this).

As you can see, that shared_ptr(p) construction creates a new count with new deleter for that p, so nothing good can come off it. It really is the best to think of std::shared_ptr<T>::get as strictly an observer, and using it to deal with lifetime management is a telltale sign that there is something wrong going on.

On the other hand, std::unique_ptr<T> has release, which is exactly what you need when you need to step in and deal with ownership yourself for an instant. Perhaps you can change your design to use std::unique_ptr<T>? It's always possible to create a std::shared_ptr<T> out of it if you need to, eventually. (Although while the std::shared_ptr<T> picks the deleter from the std::unique_ptr<T>, you still need special treatment in the array case as you probably want std::shared_ptr<T*> from std::unique_ptr<T[]>.)

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