C++智能指针循环引用破解
C智能指针循环引用破解智能指针在管理动态内存时可能遇到循环引用问题导致内存泄漏。weak_ptr是打破循环引用的关键工具它不增加引用计数。循环引用发生在两个对象互相持有shared_ptr。#include#include#include#includestruct LeakyNode {std::string name;std::shared_ptr next;explicit LeakyNode(const std::string n) : name(n) {std::cout LeakyNode name created\n;}~LeakyNode() {std::cout LeakyNode name destroyed\n;}};void circular_reference_problem() {auto a std::make_shared(A);auto b std::make_shared(B);a-next b;b-next a;std::cout Reference counts:\n;std::cout a use_count: a.use_count() \n;std::cout b use_count: b.use_count() \n;}shared_ptr循环引用导致内存泄漏。struct Node {std::string name;std::shared_ptr next;std::weak_ptr prev;explicit Node(const std::string n) : name(n) {std::cout Node name created\n;}~Node() {std::cout Node name destroyed\n;}};void weak_ptr_break_cycle() {auto a std::make_shared(A);auto b std::make_shared(B);a-next b;b-prev a;std::cout a use_count: a.use_count() \n;std::cout b use_count: b.use_count() \n;if (auto locked b-prev.lock()) {std::cout bs prev: locked-name \n;}}weak_ptr的lock方法获取临时shared_ptr。void weak_ptr_methods() {auto shared std::make_shared(42);std::weak_ptr weak(shared);if (auto locked weak.lock()) {std::cout Locked value: *locked \n;std::cout Expired: weak.expired() \n;}shared.reset();if (weak.expired()) {std::cout weak_ptr expired\n;}}二叉树使用weak_ptr避免循环。struct TreeNode {int value;std::shared_ptr left;std::shared_ptr right;std::weak_ptr parent;explicit TreeNode(int v) : value(v) {std::cout TreeNode value created\n;}~TreeNode() {std::cout TreeNode value destroyed\n;}std::shared_ptr get_parent() const {return parent.lock();}};void tree_example() {auto root std::make_shared(1);auto left std::make_shared(2);auto right std::make_shared(3);root-left left;root-right right;left-parent root;right-parent root;if (auto p left-get_parent()) {std::cout Parent of left child: p-value \n;}}enable_shared_from_this解决this获取shared_ptr的问题。class AsyncOp : public std::enable_shared_from_this {int id_;public:explicit AsyncOp(int id) : id_(id) {}std::shared_ptr get_shared() {return shared_from_this();}void start() {auto self shared_from_this();std::thread([self]() {std::this_thread::sleep_for(std::chrono::milliseconds(100));std::cout AsyncOp self-id_ completed\n;}).detach();}int id() const { return id_; }};void enable_shared_example() {auto op std::make_shared(42);op-start();std::this_thread::sleep_for(std::chrono::milliseconds(200));}weak_ptr在缓存系统中的应用。templateclass Cache {std::map cache_;std::mutex mtx_;public:std::shared_ptr get(const K key) {std::lock_guard lock(mtx_);auto it cache_.find(key);if (it ! cache_.end()) {if (auto ptr it-second.lock()) {std::cout Cache hit for key \n;return ptr;}}return nullptr;}void insert(const K key, std::shared_ptr value) {std::lock_guard lock(mtx_);cache_[key] value;}size_t size() const {std::lock_guard lock(mtx_);return cache_.size();}};void cache_demo() {Cache cache;auto s std::make_shared(cached_value);cache.insert(1, s);auto result cache.get(1);if (result) {std::cout Got: *result \n;}s.reset();result cache.get(1);if (!result) {std::cout Expired entry removed\n;}}weak_ptr不干扰引用计数不阻止对象销毁。void weak_ptr_lifecycle() {std::weak_ptr weak;{auto shared std::make_shared(100);weak shared;std::cout Inside scope, expired: weak.expired() \n;}std::cout Outside scope, expired: weak.expired() \n;}使用weak_ptr正确管理对象生命周期避免循环引用导致的内存泄漏。