2011-07-31 48 views
2

當我使用原始指針時,「遍歷」樹的上/下很容易,但是當我使用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_; 


}; 
+0

你的while循環沒有出現任何問題。你能發表演示問題的功能嗎? –

+2

你必須小心地從'this'中構造一個shared_ptr,因爲當共享指針超出範圍時,你可能只是在腳下自己拍攝!你必須從'std :: enable_shared_from_this'或派生出來。 –

+0

@Kerrek謝謝,可以用其他指針代替的任何想法? – smallB

回答

2

你不能從這個創建一個共享的指針,你在

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()); 

那麼,你如何得到一個共享指針,以根()?如果你想使用boost,你應該使用shared_from_this:http://www.boost.org/doc/libs/1_47_0/libs/smart_ptr/enable_shared_from_this.html

你可以使用普通的指針,或者將類的外部函數或靜態函數作爲參數,以shared_ptr作爲參數。

+1

+1或複製'node_ptr tmp = node_ptr(新節點(* this));' – Tom

+0

是的,複製通常是有意義的。不是爲了尋找樹根的特殊情況。 – 2011-08-01 00:12:19

1

是否有任何理由,你應該操縱智能指針?既然你在編寫同步代碼,而且結構看起來並不懶惰,你並不真正關心所有權問題 - 這是一個愚蠢的遍歷。所以可以使用原始指針。