當我使用原始指針時,「遍歷」樹的上/下很容易,但是當我使用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和這不是我的父想。
任何線索?
編輯
這是真正的代碼:
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_;
};
你的while循環沒有出現任何問題。你能發表演示問題的功能嗎? –
你必須小心地從'this'中構造一個shared_ptr,因爲當共享指針超出範圍時,你可能只是在腳下自己拍攝!你必須從'std :: enable_shared_from_this'或派生出來。 –
@Kerrek謝謝,可以用其他指針代替的任何想法? – smallB