使用weak_ptr可打破shared_ptr循环引用,避免内存泄漏。在双向关联中,如父子对象,一方用shared_ptr,另一方用weak_ptr,确保引用链可断,对象能正常析构。

C++
shared_ptr
weak_ptr
当我们谈论
shared_ptr
我个人在项目中就遇到过几次,最典型的是双向链表或父子关系中,两个对象互相持有对方的
shared_ptr
shared_ptr
shared_ptr
weak_ptr
weak_ptr
lock()
shared_ptr
weak_ptr
shared_ptr
weak_ptr
weak_ptr
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <memory>
#include <vector>
// 前向声明
class Child;
class Parent {
public:
std::shared_ptr<Child> child;
~Parent() {
std::cout << "Parent destroyed." << std::endl;
}
};
class Child {
public:
std::weak_ptr<Parent> parent; // 使用 weak_ptr 打破循环
~Child() {
std::cout << "Child destroyed." << std::endl;
}
};
void test_cyclic_reference() {
std::cout << "--- 测试 shared_ptr 循环引用 (使用 weak_ptr 优化) ---" << std::endl以上就是C++shared_ptr循环引用优化与性能策略的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号