shared_ptr
make_shared<T> 分配创建传入参数的对象,get() 获取原始指针 reset() 减少一个引用计数,use_count()查看引用计数
auto it = make_shared<int> (19); //声明一个it的对象
cout << *it<<" "<<it.use_count()<<endl; //19 1 计数内容
shared_ptr<int> it1 = it; // it1也指向it的内存地址
cout << *it<<" "<<it1.use_count()<<" "<<it.use_count()<<endl; //19 2 2
int* i2 = it.get();//get函数获取原始对象的指针
cout << *i2<<endl; //19
it.reset(); // 将it的引用计数减少1 it也不能使用了
cout << *it1<<" "<<it1.use_count()<<endl; //19 1
unique_ptr C++14实现的
独占指针,禁止复制,可用move()进行转移给其他unique_ptr
make_unique 自己实现
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args ) {
return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}
weak_ptr 解决资源未释放 没有* ->运算符,只能检查shared_ptr是否存在 expired()函数当资源未释放时返回false。
使用shared_ptr的反例
struct A;
struct B;
struct A {
std::shared_ptr<B> pointer;
~A() {
std::cout << "A 被销毁" << std::endl;
}
};
struct B {
std::shared_ptr<A> pointer;
~B() {
std::cout << "B 被销毁" << std::endl;
}
};
int main() {
auto a = std::make_shared<A>();
auto b = std::make_shared<B>();
a->pointer = b;
b->pointer = a;
}