Home > Article > Backend Development > How can I safely pass a `std::shared_ptr` of \"this\" from a parent object to its child object in C ?
How to Use std::shared_ptr to Pass a Reference of "this"
In object-oriented programming, it is common for objects to maintain relationships with each other. This often involves objects holding references to each other, allowing for communication and data sharing. One way to manage object references in C is through the use of smart pointers, particularly std::shared_ptr.
Consider the hypothetical scenario where class A holds a list of std::shared_ptr references to objects of class B, where each B object also needs to hold a reference to its parent A object. This poses a challenge: how can class A safely pass a std::shared_ptr of itself (this) to its child B?
A straightforward approach might be to try something like child->setParent(this);, but this is incorrect because this is not a valid std::shared_ptr. The solution lies in the use of std::enable_shared_from_this.
Introducing std::enable_shared_from_this
std::enable_shared_from_this is a base class that allows objects to return a std::shared_ptr reference to themselves. By inheriting from std::enable_shared_from_this, class A gains the ability to call .shared_from_this() to obtain a shared pointer to its own instance.
Solution Using std::enable_shared_from_this
In the modified code below, class A is made to inherit from std::enable_shared_from_this, and the child->setParent() call now uses .shared_from_this():
<code class="cpp">class A : public std::enable_shared_from_this<A> { public: void addChild(std::shared_ptr<B> child) { children.push_back(child); child->setParent(shared_from_this()); } private: // Note the use of std::weak_ptr here std::list<std::weak_ptr<B>> children; };</code>
In this updated code:
This approach solves the problem of passing a std::shared_ptr of "this" from a parent A object to its child B object. By using std::enable_shared_from_this and managing circular dependencies with std::weak_ptr, a safe and effective reference sharing mechanism is achieved.
The above is the detailed content of How can I safely pass a `std::shared_ptr` of \"this\" from a parent object to its child object in C ?. For more information, please follow other related articles on the PHP Chinese website!