Home > Backend Development > C++ > body text

How to Prevent Circular Dependencies When Using std::shared_ptr of \'this\'?

Linda Hamilton
Release: 2024-10-29 04:43:29
Original
523 people have browsed it

How to Prevent Circular Dependencies When Using std::shared_ptr of

std::shared_ptr of "this": Understanding Circular Dependencies

Inheriting from std::enable_shared_from_this is the key to resolving the "std::shared_ptr of this" conundrum. By enabling this, you can invoke .shared_from_this() to obtain a shared pointer to the current object. However, this introduces a potential circular dependency between the parent and child objects.

To address this issue, it's recommended to use std::weak_ptr for the child's reference to the parent. This prevents the formation of strong circular references and protects against resource leaks. The modified code demonstrates how to implement this approach:

<br>class A : public std::enable_shared_from_this<a> {<br>public:</a></p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">void addChild(std::shared_ptr<B> child) {
    children.push_back(child);
    child->setParent(shared_from_this());
}
Copy after login

private:

std::list<std::weak_ptr<B>> children;
Copy after login

};

class B {
public:

void setParent(std::shared_ptr<A> parent) {
    this->parent = parent;
}
Copy after login

private:

std::shared_ptr<A> parent;
Copy after login

};

It's important to note that invoking .shared_from_this() requires that the current object is managed by std::shared_ptr at the time of the call. This implies that creating such objects on the stack is no longer possible, and calling .shared_from_this() from a constructor or destructor is generally not recommended.

The above is the detailed content of How to Prevent Circular Dependencies When Using std::shared_ptr of \'this\'?. 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
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!