Home > Backend Development > C++ > How Can I Safely Pass a `std::shared_ptr` of `this` to a Related Object?

How Can I Safely Pass a `std::shared_ptr` of `this` to a Related Object?

DDD
Release: 2024-10-28 21:01:30
Original
836 people have browsed it

How Can I Safely Pass a `std::shared_ptr` of `this` to a Related Object?

Understanding the "std::shared_ptr of this" Dilemma

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.

Solution: 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>
Copy after login

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>
Copy after login

Precautions

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template