当我使用原始指针时,在树上“遍历”非常容易,但是当我使用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/