一、unique_ptr
unique_ptr 是从 C++ 11 开始,定义在 <memory> 中的智能指针(smart pointer)。它持有对对象的独有权,即两个 unique_ptr 不能指向一个对象,不能进行复制操作只能进行移动操作。
释放 nullptr 不犯法!
1、unique_ptr初始化
//c11
unique_ptr<int> up; // 空指针,nullptr
unique_ptr<int> up(new int(100)); // 分配了内存
int *p = new int(100); // 传入指向动态内存的指针
unique_ptr<int> up(p);
//c14才出现
unique_ptr<int> up1 = make_unique<int>(100);
auto up2 = make_unique<int>(100);
2、unique_ptr不支持:赋值、拷贝
unique_ptr<int> up1(new int(100));
unique_ptr<int> up2 = up1; // 不支持 =号初始化赋值
unique_ptr<int> up3(up1); // 不支持 拷贝
unique_ptr<int> up4; // 不支持 赋值
up4 = up1;
3、release
unique_ptr<int> up1(new int(100);
unique_ptr<int> up2(up1.release()); //release 切断智能指针与所指对象的联系,并返回裸指针
4、reset
unique_ptr<int> up(new int(100));
up.reset(); // 释放内存,并置空
//up.reset(nullptr);
unique_ptr<int> up1(new int(100));
up1.reset(new int(101)); // 释放原内存,开辟新内存
5、移动语义
移动语义不仅可以 unique_ptr 转移到另一个 unique_ptr,还可以 unique_ptr 转移到另一个 shared_ptr。
unique_ptr<int> func()
{
return unique_ptr<int>(new int(100));
}
int main()
{
// 第一种,从函数 返回 临时对象
unique_ptr<int> up1 = func();
// 第二种,使用 move
unique_ptr<int> up2(new int(100));
unique_ptr<int> up3 = move(up2); //此时up2指向空,up3指向原来up2指向的内存
// 第三种,使用 release
unique_ptr<int> up4(new int(99));
unique_ptr<int> up5(up4.release());
// 第四种,使用 reset + release
unique_ptr<int> up6(new int(99));
unique_ptr<int> up7;
up7.reset(up6.release());
return 0;
}
6、= nullptr,释放资源,置空指针
unique_ptr<int> up(new int(100));
up = nullptr; // 同 up.reset();
7、解引用
unique_ptr<int> up(new int(100));
cout << *up << endl;
8、get,获取普通指针
unique_ptr<int> up(new int(100));
int * p = up.get(); // 返回指向动态内存的普通指针
9、swap,交换两个智能指针
unique_ptr<int> up1(new int(100));
unique_ptr<int> up2(new int(99));
swap(up1, up2); // 交换方式一
cout << *up1 << endl;
up1.swap(up2); // 交换方式二
cout << *up1 << endl;
10、删除器
void mydelete(int *p) // 有参数
{
delete p;
p = nullptr;
cout << "memory has been released" << endl;
}
int main()
{
// typedef void(*fp)(int*);
// unique_ptr<int, fp> up(new int(100), mydelete);
unique_ptr<int, decltype(mydelete)*> up(new int(100), mydelete); // 第一个参数相当于是函数参数
return 0;
}