c++ - 使用shared_ptr

标签 c++ shared-ptr

当我使用原始指针时,在树上“遍历”非常容易,但是当我使用shared_ptr而不是内置指针时,情况并非如此。我的意思是我不能这样做(没有副作用):

shared_ptr<T> p(some_shared);

while (p->parent_)//here I'm assuming that the type pointed to has parent_ member
{
p = p->parent_;
}

这对我不起作用,因为看起来它在分配给 p 时重置了 p->parent,而这不是我想要的。

有什么线索吗?

编辑

这是真实的代码:

template<class Key_T, class Value_T>
class Node
{

public:
    /*typedefs*/
    #define ptr_type std::shared_ptr

    typedef Key_T key_type;
    typedef ptr_type<key_type> key_ptr;
    typedef Value_T value_type;
    typedef ptr_type<value_type> value_ptr;

    typedef Colors color_type;
    typedef color_type* color_raw_ptr;
    typedef ptr_type<color_type> color_ptr;

    typedef std::pair<key_ptr,value_ptr> data_type;
    typedef ptr_type<data_type> data_ptr;

    typedef Node<key_type,value_type> node_type;
    typedef node_type* node_raw_ptr;
    typedef ptr_type<node_type> node_ptr; 
    explicit Node()
    {}
    explicit Node(const key_type& key,
        const value_type& value, 
        const color_type& color,
        node_ptr parent = nullptr,
        node_ptr left = nullptr,
        node_ptr right = nullptr);

        ~Node()
    {
        cout << "Bye now";
    }

    const node_ptr& root()const
    {
        node_ptr tmp = node_ptr(this);
        while (tmp->parent_)
        {///this seems to reset resources

            tmp = tmp->parent_;

        }

        return tmp;
    }
private:

    data_ptr data_;
    color_ptr color_;

    node_ptr parent_;
    node_ptr left_;
    node_ptr right_;


};

最佳答案

您不能像在中那样从中创建共享指针

node_ptr tmp = node_ptr(this);

当您创建共享指针时,它会假定分配给它的指针的所有权 - 因此在重新分配 tmp 时会删除该指针。

关于shared_ptr的问题是:http://www.boost.org/doc/libs/1_47_0/libs/smart_ptr/sp_techniques.html#from_this

您需要始终像这样创建共享指针:

node_ptr tmp = node_ptr(new node());

那么如何获得 root() 的共享指针呢?如果您要使用 boost,您将拥有shared_from_this:http://www.boost.org/doc/libs/1_47_0/libs/smart_ptr/enable_shared_from_this.html

您可以使用普通指针,或者将函数设置为类的外部函数或静态函数,并将shared_ptr作为参数。

关于c++ - 使用shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6892769/

相关文章:

c++ - 用于取值和赋值的矩阵下标运算符

c++ - 在基类中调用 shared_from_this() 时的 bad_weak_ptr

c++ - 初始化 shared_ptr ,当对象需要默认构造函数时

c++ - std::tr1 中的 shared_ptr

c++11 - 我应该如何构造一个要使用 std::shared_ptr 管理的实例?

c++ - shared_ptr SIGSEGV 中的无序映射

C++ Pixel Grabber 错误的 RGB 值

c++ - 在父类中包含子类的 typedef

c++ - CDHtmlDialog 没有加载最新版本的 IE?

c++ - 如何获取ethtool设置?