In smart pointer usage, often a scenario arises where two related objects, A and B, require access to each other. However, passing std::shared_ptr to establish this connection becomes challenging.
For instance, consider class A, the parent, which needs to add a child object B. The parent's addChild method should ideally pass a std::shared_ptr to the child, so it can reference the parent.
However, a direct child->setParent(this) attempt fails due to the this pointer being an rvalue. To resolve this, C offers std::enable_shared_from_this.
std::enable_shared_from_this is a class template that facilitates sharing of an object via std::shared_ptr. By inheriting from it, you gain access to shared_from_this(), which provides the necessary std::shared_ptr, as seen in the modified code:
<code class="cpp">class A : public std::enable_shared_from_this<A> { ... child->setParent(shared_from_this()); // now valid };</code>
Additionally, to prevent circular dependencies that could lead to memory leaks, it's advisable to use std::weak_ptr for children that depend on their parent's existence:
<code class="cpp">std::list<std::weak_ptr<B>> children; // now using weak_ptr</code>
It's important to note that .shared_from_this() should only be called when the calling object is managed by std::shared_ptr. This means that it cannot be created on the stack and typically cannot be called in constructors or destructors.
The above is the detailed content of How Can I Safely Pass a `std::shared_ptr` of `this` to a Related Object?. For more information, please follow other related articles on the PHP Chinese website!