c++智能指针shared_ptr示例

2021-02-15  本文已影响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
上一篇 下一篇

猜你喜欢

热点阅读