美文网首页
c++智能指针shared_ptr示例

c++智能指针shared_ptr示例

作者: 一路向后 | 来源:发表于2021-02-15 19:04 被阅读0次

    1.示例源码

    #include <iostream>
    #include <string>
    #include <tr1/memory>
    
    using namespace std;
    
    class Test
    {
    public:
        Test(string name)
        {
            p_name = name;
            cout << p_name << " constructor" << endl;
        }
        ~Test()
        {
            cout << p_name << " destructor" << endl;
        }
    
    private:
        string p_name;
    };
    
    int main(int argc, char **argv)
    {
        /*类对象, 原生指针构造*/
        shared_ptr<Test> pstr1(new Test("object"));
    
        cout << "pstr1的引用计数: " << pstr1.use_count() << endl;
    
        shared_ptr<Test> pstr2 = pstr1;
    
        cout << "pstr1的引用计数: " << pstr2.use_count() << endl;
    
        return 0;
    }
    

    2.编译源码

    $ g++ -o example example.cpp
    

    3.运行及其结果

    $ ./example
    object constructor
    pstr1的引用计数: 1
    pstr1的引用计数: 2
    object destructor
    

    相关文章

      网友评论

          本文标题:c++智能指针shared_ptr示例

          本文链接:https://www.haomeiwen.com/subject/upxmxltx.html