rhughes
rhughes

Reputation: 9583

Passing `this` to child object

Is this method of passing and storing this to a child object still considered 'acceptable' when using C++17, or is there a more appropriate method, in line with the language and standard?

I am specifically asking regarding passing and storing the Parent object as a plain pointer.

class Child
{
public:
    void SetParent(Parent* p)
    {
        _parent = p;
    }
private:
    Parent* _parent;
};

class Parent
{
public:
    void MyMethod()
    {
        Child c;
        c.SetParent(this);
    }
};

Upvotes: 1

Views: 675

Answers (1)

Mark Ingram
Mark Ingram

Reputation: 73605

Post-C++11 you can use std::weak_ptr<Parent>, assuming you're using std::shared_ptr<Parent> (and inherit from std::enable_shared_from_this in order to generate a std::shared_ptr or std::weak_ptr internally).

Aside from that, yes, it's still acceptable to use a raw pointer to represent lack of ownership or back pointer (until the committee adds some kind of std::owned_ptr<T> / std::ptr_view<T> class).

Upvotes: 3

Related Questions