use*_*508 39 c++ boost shared-ptr
boost :: shared_ptr可以释放存储的指针而不删除它吗?
我可以看到文档中没有发布功能,也在FAQ中解释了为什么它不提供发布功能,类似于发布不能在不唯一的指针上完成.我的指针是独一无二的.我该如何发布我的指针?或者哪个提升智能指针类使用,这将允许我释放指针?我希望你不要说使用auto_ptr :)
sel*_*tze 29
别.Boost的FAQ条目:
Q.为什么shared_ptr不提供release()函数?
一.shared_ptr不能放弃所有权,除非它是唯一的()因为另一个副本仍将销毁该对象.
考虑:
Run Code Online (Sandbox Code Playgroud)shared_ptr<int> a(new int); shared_ptr<int> b(a); // a.use_count() == b.use_count() == 2 int * p = a.release(); // Who owns p now? b will still call delete on it in its destructor.
此外,release()返回的指针很难可靠地解除分配,因为源shared_ptr可能是使用自定义删除器创建的.
因此,如果它是唯一指向您的对象的shared_ptr实例(当unique()返回true时)并且该对象不需要特殊的删除器,这将是安全的.如果您使用了这样的.release()函数,我仍然会质疑您的设计.
Kir*_*sky 22
你可以使用假删除器.然后指针实际上不会被删除.
struct NullDeleter {template<typename T> void operator()(T*) {} };
// pp of type some_t defined somewhere
boost::shared_ptr<some_t> x(pp, NullDeleter() );
Run Code Online (Sandbox Code Playgroud)
孩子们,不要在家里这样做:
// set smarty to point to nothing
// returns old(smarty.get())
// caller is responsible for the returned pointer (careful)
template <typename T>
T* release (shared_ptr<T>& smarty) {
// sanity check:
assert (smarty.unique());
// only one owner (please don't play games with weak_ptr in another thread)
// would want to check the total count (shared+weak) here
// save the pointer:
T *raw = &*smarty;
// at this point smarty owns raw, can't return it
try {
// an exception here would be quite unpleasant
// now smash smarty:
new (&smarty) shared_ptr<T> ();
// REALLY: don't do it!
// the behaviour is not defined!
// in practice: at least a memory leak!
} catch (...) {
// there is no shared_ptr<T> in smarty zombie now
// can't fix it at this point:
// the only fix would be to retry, and it would probably throw again
// sorry, can't do anything
abort ();
}
// smarty is a fresh shared_ptr<T> that doesn't own raw
// at this point, nobody owns raw, can return it
return raw;
}
Run Code Online (Sandbox Code Playgroud)
现在,有没有办法检查引用计数的所有者总数是否> 1?
归档时间: |
|
查看次数: |
30954 次 |
最近记录: |