zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    epoll 实现回射服务器
    select函数的介绍和使用
    期末项目需求分析报告
    Spring AOP Capabilities and Goals
    Domain Logic approaches
    Lamda Expression
    CDI furture
    23种设计模式
    connector for python
    Spring reference
  • 原文地址:https://www.cnblogs.com/justin_s/p/1903869.html
Copyright © 2011-2022 走看看