c++智能指针

时间:2024-10-12 13:33:08

#include <iostream>

#include <memory> // 头文件

using namespace std;

/**

* @brief The Source class

* 被智能指针管理的堆内存资源对象类

*/

class Source

{

private:

string name;

public:

Source(string name):name(name)

{

cout << name << "构造函数" << endl;

}

~Source()

{

cout << name << "析构函数" << endl;

}

void show()

{

cout << name << "成员函数" << endl;

}

};

int main()

{

shared_ptr<Source> sp1 = make_shared<Source>("A");

cout << sp1.use_count() << endl; // 1

shared_ptr<Source> sp2(sp1); // 拷贝构造函数

cout << sp1.use_count() << " " << sp2.use_count() << endl; // 2 2

sp2.reset(); // 解除sp2对A的管理

cout << sp1.use_count() << " " << sp2.use_count() << endl; // 1 0

shared_ptr<Source> sp3;

sp3 = sp1; // 赋值运算符

cout << sp1.use_count() << " " << sp3.use_count() << endl; // 2 2

shared_ptr<Source> sp4 = sp3; // 拷贝构造函数

cout << sp1.use_count() << endl; // 3

// shared_ptr<Source> sp5(sp4.get()); 错误

sp4.get()->show();

{ // 局部代码块

shared_ptr<Source> sp6;

sp6 = sp1;

cout << sp1.use_count() << endl; // 4

}

cout << sp1.use_count() << endl; // 3

cout << "主函数结束" << endl;

return 0;

}