zoukankan      html  css  js  c++  java
  • C++中 shared_ptr的拷贝和赋值——引用计数理解

      当进行拷贝或赋值操作时,每个shared_ptr都会纪录有多少个其他shared_ptr指向相同的对象:

      auto p = make_shared<int>(50);//p指向的对象只有p一个引用者
      auto q = p; //p和q指向相同对象,此对象有两个引用者;
    

      智能指针类能记录有多少个shared_ptr指向相同的对象,并能在恰当的时候自动释放对象!

      关于shared_ptr的引用计数测试demo:

    #include <iostream>
    #include <memory>
    #include <vector>
    using namespace std;
    int main()
    {
        vector<shared_ptr<int>> intPtr;
        vector<shared_ptr<int>> intPtr2;
        for (int i = 0; i < 10; ++i) {
            intPtr.emplace_back(make_shared<int>(i));
        }
        for (int i = 0; i < 10; ++i) {
            cout << "intPtr " << i << " = " << *intPtr.at(i) << endl;        
        }
    
        intPtr2 = intPtr;
        /*
        cout << "2:  intPtr[0].use_count() = " << intPtr[0].use_count() << endl;
        cout << "2:  intPtr2[0].use_count() = " << intPtr2[0].use_count() << endl;
        */
    
        cout << "intPtr[0]  = " << intPtr[0] << endl;
        cout << "intPtr2[0] = " << intPtr2[0] << endl;
    
        intPtr[0] = make_shared<int>(50);
    
        cout << "3:  intPtr[0].use_count()  = " << intPtr[0].use_count() << endl;
        cout << "3:  intPtr2[0].use_count() = " << intPtr2[0].use_count() << endl;
    
        cout << "intPtr[0]  = " << intPtr[0] << endl;
        cout << "intPtr2[0] = " << intPtr2[0] << endl;
    
        cout << "intPtr[0]  = " << *intPtr[0] << endl;
        cout << "intPtr2[0] = " << *intPtr2[0] << endl;
    
    
        return 0;
    }
  • 相关阅读:
    mac c++编译出现segmentation fault :11错误
    ssh 连接缓慢解决方法
    237. Delete Node in a Linked List
    203. Remove Linked List Elements
    Inversion of Control Containers and the Dependency Injection pattern
    82. Remove Duplicates from Sorted List II
    83. Remove Duplicates from Sorted List
    SxsTrace
    使用CCleaner卸载chrome
    decimal and double ToString problem
  • 原文地址:https://www.cnblogs.com/create-serenditipy/p/13393511.html
Copyright © 2011-2022 走看看