栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

[modern c++] std::weak

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

[modern c++] std::weak

std::weak_ptr

It must be converted to std::shared_ptr in order to access the referenced object.

std::weak_ptr is used to track the object, and it is converted to std::shared_ptr to assume temporary ownership.If the original std::shared_ptr is destroyed at this time, 
the object's lifetime is “extended” until the temporary std::shared_ptr is destroyed as well.

Another use for std::weak_ptr is to break reference cycles formed by objects managed by std::shared_ptr. If such cycle is orphaned (i.e., there are no outside shared pointers into the cycle), the shared_ptr reference counts cannot reach zero and the memory is leaked. To prevent this, one of the pointers in the cycle can be made weak.


1. 不能直接访问,必须通过 lock() 成员函数返回一个 std::shared_ptr 后用来访问,这也会引起一次 std::shared_ptr 指向对象的计数增加;
2. 如果std::weak_ptr在通过lock() 获得一个 std::shared_ptr ,那么这会增加一次被管理对象的计数,此时即便原来的 std::shared_ptr 被销毁了,但是由于新创建了一个临时的 std::shared_ptr ,所以也
   不会触发被管理对象的释放,也就是说会起到 “延长” 生命周期的作用。
   

Demo of resolving reference cycle:

#include 
#include 
#include 
 
class Node {
    char id;
    std::variant, std::shared_ptr> ptr;
  public:
    Node(char id) : id{id} {}
    ~Node() { std::cout << "  '" << id << "' reclaimedn"; }
    
    void assign(std::weak_ptr p) { ptr = p; }
    void assign(std::shared_ptr p) { ptr = p; }
};
 
enum class shared { all, some };
 
void test_cyclic_graph(const shared x) {
 
    auto A = std::make_shared('A');
    auto B = std::make_shared('B');
    auto C = std::make_shared('C');
 
    A->assign(B);
    B->assign(C);
 
    if (shared::all == x) {
        C->assign(A);
        std::cout << "All links are shared pointers";
    } else {
        C->assign(std::weak_ptr(A));
        std::cout << "One link is a weak_ptr";
    }
    
    std::cout << "nLeaving...n";
}
 
int main() {
    test_cyclic_graph(shared::some);
    test_cyclic_graph(shared::all); // produces a memory leak
}

   
为什么 std::weak_ptr 可以用来解决 reference cycle 问题?
如果 使用 lock() 获得一个临时 std::shared_ptr 后不释放,那么不还是一样存在问题么?

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/938188.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号