unique_ptr
#include <iostream>
#include <memory>
using namespace std;
int main()
{//智能指针unique_ptr 原始指针void* int* char*// 1. 在任意时刻,都只能有一个指针管理内存// 2. 在指针超出作用域时,会自动释放// 3. 指针类型不可拷贝,只可以move// int num = 12;int* p = new int(100);// *p = num;unique_ptr<int> up = make_unique<int>(*p); //使用make_unique// unique_ptr<int> up(p); //传入指针cout << *up << endl; //出了作用域自动销毁了cout << p << endl;cout << up.get() << endl;}
shared_ptr
#include <iostream>
#include <memory>
using namespace std;
int main()
{// shared_ptr 共享指针//可以共享数据//常量类型shared_ptr<int> p = make_shared<int>(10);// shared_ptr<int> pp = make_shared<int>{new int(11)};// cout << "value =" << pp << endl;cout << "value =" << p << endl;cout << "use count = " << p.use_count();shared_ptr<int> pp = p; // copycout << "p use count = " << p.use_count() << endl;cout << "pp use count = " << pp.use_count() << endl;*pp = 12; //两个都会发生改变cout << "p value =" << *p << endl;cout << "pp value =" << *pp << endl;// pp = nullptr; //设置为null;会清理2不会清理1p = nullptr; //设置为null;会清理1不会清理2cout << "p use count = " << p.use_count() << endl;cout << "pp use count = " << pp.use_count() << endl;//自定义类型return 0;
}
不能将shared_ptr转为unique_ptr,但是可以将unique_ptr转为shared_ptr,通过std::move函数。
常见的设计
将你的函数返回unique_ptr是一种常见的设计模式,这样可以提高代码的复用度,你可以随时改变shared_ptr
#include <iostream>
#include <memory>
using namespace std;std::unique_ptr<int> get_fun()
{// cout << p << endl;unique_ptr<int> p = make_unique<int>(10);*p = 121212121;return p;
}
int main()
{unique_ptr<int> p = make_unique<int>(12);cout << "p.get()=" << p.get() << endl; //shared_ptr<int> sp = move(p); //转换cout << "sp count = " << sp.use_count() << endl;cout << "p.get()=" << p.get() << endl; //不可以使用了shared_ptr<int> sp3 = get_fun();if (sp3) {cout << "*sp3 = " << *sp3 << endl; //不可转换cout << "sp3.use_count()" << sp3.use_count() << endl;// sp3.use_count();} else {cout << "error" << endl;}return 0;
}
weak_ptr
没有所有权,不能调用->和解引用*
#include <iostream>
#include <memory>
using namespace std;std::unique_ptr<int> get_fun()
{// cout << p << endl;unique_ptr<int> p = make_unique<int>(10);*p = 121212121;return p;
}
int main()
{shared_ptr<int> p = make_shared<int>(122);weak_ptr<int> wp(p);*p = 120;cout << "p value = " << *p << endl;shared_ptr<int> pp = wp.lock(); //转为 共享指针cout << "pp value = " << *pp << endl;cout << "shared_prt count = " << p.use_count() << endl;cout << "wpak_prt count = " << wp.use_count() << endl;cout << " wp.expired= " << wp.expired() << endl;return 0;
}