1. Overview of unique_ptr
1.1 Introduction to unique_ptr
unique_ptr is a smart pointer defined in <memory> since C ++ 11. It holds the exclusive right to the object, that is, two unique_ptr can not point to an object, can not be copied operation can only be moved.
1.2 Initialization of unique_ptr
//常规初始化
unique_ptr<int> up(new int(100));
//make_unique 初始化
unique_ptr<int> up1 = make_unique<int>(100); //C++14中才出现
auto up2 = make_unique<int>(100);
Two. Unique_ptr common operations
2.1 Operation not supported by unique_ptr
unique_ptr<int> up(new int(100));
/*
unique_ptr<int> up2 = up;
unique_ptr<int> up3(up);
unique_ptr<int> up4;
up4 = up;
*/
2.2 Mobile semantics
#include <iostream>
using namespace std;
unique_ptr<int> func()
{
return unique_ptr<int>(new int(100));
}
int main()
{
//第一种接收从函数返回的临时对象
unique_ptr<int> up = func();
//第二种使用move函数
unique_ptr<int> up2(new int(100));
unique_ptr<int> up3 = move(up2); //此时up2指向空,up3指向原来up2指向的内存
return 0;
}
2.3 release
unique_ptr<int> up(new int(100);
unique_ptr<int> up2(up.release()); //release 切断智能指针与所指对象的联系,并返回裸指针
2.4 reset
//1.reset不带参数:释放所指对象资源,并将指针指向空
unique_ptr<int> up(new int(100));
up.reset();
if (!up)
{
cout << "up是空指针" << endl;
}
//2.reset带参数:释放智能指针所指的对象并将智能指针指向参数
unique_ptr<int> up1(new int(100));
up1.reset(new int(101));
if (up1)
{
cout << "up1不为空" << endl;
}
2.5 = nullptr frees resources and sets null pointer
unique_ptr<int> up(new int(100));
up = nullptr;
2.6 Point to an array
unique_ptr<int[]> up(new int[10]); //如果指向一个数组,<>中需要带上 [],否则将导致内存泄漏以及不可以使用下面的[]索引
up[1] = 100;
2.7 get
unique_ptr<int> up(new int(100));
int * p = up.get(); //返回裸指针
2.8 * Dereference
unique_ptr<int> up(new int(100));
cout << "up的值:" << *up << endl;
2.9 swap
unique_ptr<int> up(new int(100));
unique_ptr<int> up2(new int(9));
//swap的作用:交换两个智能指针所指向的对象
swap(up, up2); //第一种调用方式
cout << "up的值:" << *up << endl;
up.swap(up2); //第二种调用方式
cout << "up的值:" << *up << endl;
2.10 Convert unique_ptr to shared_ptr
#include <iostream>
using namespace std;
unique_ptr<int> func()
{
return unique_ptr<int>(new int(100));
}
int main()
{
//如果unique_ptr作为右值,可以将其转换为shared_ptr
//第一种
unique_ptr<int> up(new int(100));
shared_ptr<int> sp = move(up);
//第二种
shared_ptr<int> sp1 = func();
return 0;
}
3. Remover
3.1 Specified deleter
#include <iostream>
using namespace std;
void mydelete(int *p)
{
delete p;
p = nullptr;
cout << "内存已经被释放" << endl;
}
int main()
{
typedef void(*fp)(int*);
unique_ptr<int, fp> up(new int(100), mydelete);
//uniqeu_ptr指定删除器总结:
//需要在<>中指定函数类型
//因为需要在<>指定函数类型,所以unique_ptr的灵活性受到了限制,不同的函数类型使得unique_ptr的类型不同,类型不同就不可以放在同一个容器中
return 0;
}