boost:shared_ptr

The shared_ptr class template stores a pointer to a dynamically allocated object, typically with a C++ new-expression. The object pointed to is guaranteed to be deleted when the last shared_ptr pointing to it is destroyed or reset.

要考虑的是拷贝和赋值的情况,以及比较运算符,幸好这都在shared_ptr的设计之下。

但,shared_ptr不能正确的处理数组指针,如果需要,可以考虑shared_arry

而且,需要注意循环计数的情况,以及在构造函数中的使用。

Q. Why doesn't shared_ptr (or any of the other Boost smart pointers) supply an automatic conversion to T*?

A. Automatic conversion is believed to be too error prone.

Y

ou can derive from enable_shared_from_this and then you can use "shared_from_this()" instead of "this" to spawn a shared pointer to your own self object.

Example in the link:

class Y: public enable_shared_from_this<Y>
{
public:

    shared_ptr<Y> f()
    {
        return shared_from_this();
    }
}

int main()
{
    shared_ptr<Y> p(new Y);
    shared_ptr<Y> q = p->f();
    assert(p == q);
    assert(!(p < q || q < p)); // p and q must share ownership
}

It's a good idea when spawning threads from a member function to boost::bind to a shared_from_this() instead of this. It will ensure that the object is not released.

原文链接: https://www.cnblogs.com/justin_s/archive/2010/12/12/1903869.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    boost:shared_ptr

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/18682

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月7日 下午7:30
下一篇 2023年2月7日 下午7:33

相关推荐