Search code examples
c++shared-ptr

Using shared_ptr


When I'm using raw pointers it is pretty easy to 'travers' up/down the tree, but when I've employed shared_ptr instead of built-in pointers it isn't so. I mean I just can't do (without side effects) just this:

shared_ptr<T> p(some_shared);

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

This doesn't work for me because it looks like it resets p->parent when it assigns to p and that's not what I want.

Any clues?

Edit

This is real code:

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_;


};

Solution

  • You cannot create a shared pointer from this as you do in

    node_ptr tmp = node_ptr(this);
    

    When you create a shared pointer, it assumes ownership of the pointer given to it - so this deletes this when tmp is reassigned.

    On the subject of shared_ptr to this: http://www.boost.org/doc/libs/1_47_0/libs/smart_ptr/sp_techniques.html#from_this

    You need to create shared pointers always like this:

    node_ptr tmp = node_ptr(new node());
    

    So how do you get a shared pointer to root()? If you would use boost, you would have shared_from_this: http://www.boost.org/doc/libs/1_47_0/libs/smart_ptr/enable_shared_from_this.html

    You can use normal pointers, or make the function external or static to the class, taking shared_ptr as an argument.