智能指针 “shared_ptr<T>” 用于代替 “new/delete” 来管理对象的生命周期。
用法:
#include <iostream>
#include <memory>
class A {
public:
A(int a);
~A();
int _a;
void print();
};
A::A(int a): _a(a) {
std::cout<< "A(int a)" << std::endl;
}
A::~A() {
std::cout<< "~A()" << std::endl;
}
void A::print() {
std::cout<< "A::print A._a: " << _a << std::endl;
}
int main() {
{
// a. 定义一个局部变量 pA 类型为 shared_ptr<A>
// b. shard_ptr<T> 包含两个成员变量
// 1. T* ptr;
// 2. int* refCount; //T类型变量的引用计数
// c. make_shared<A>(90) 在内存中创建A对象,调用A的构造函数A(int a)
// 将内存地址赋值给 pA.ptr; 同时*(pA.refCount) = 1;
std::shared_ptr<A> pA= std::make_shared<A>(90);
pA->print();
// d. 执行shared_ptr<T>的拷贝构造函数
std::shared_ptr<A> pB = pA;
pB->print();
pB->_a = 100;
pA->print();
pB->print();
}
// e. pA 和 pB 对象的作用域结束,
// 调用pA对象的析构函数,*(pA.refCount)-- *(pA.refCount) == 1;
// 调用pB对象的析构函数, *(pB.refCount)-- *(pB.refCount) == 0;
// 执行A::~A();
}
网友评论