unique_ptr指针:
unique指针禁止不同的指针指向同一对象,可用于对象的保护。
不同unique指针的赋值通过转移控制权实现,不进行指针的复制,一个对象永远只有一个unique_ptr指针指向其内容;
传值问题:unique指针不能通过值传递到函数,即在函数输入变量中不能直接传参。直接传参会导致参数的复制,要注意!个人觉得这里容易出现使用问题。
操作方法:
1. 在构建函数时赋值;
2. 通过reset函数重新指定对象;
3. 通过release释放空间;release释放后,unique_ptr无对象,可能会导致悬浮指针。
// 智能指针的创建
unique_ptr<int> u_i; //创建空智能指针
u_i.reset(new int(3)); //绑定动态对象
unique_ptr<int> u_i2(new int(4));//创建时指定动态对象
unique_ptr<T,D> u(d); //创建空 unique_ptr,执行类型为 T 的对象,用类型为 D 的对象 d 来替代默认的删除器 delete
// 所有权的变化
int *p_i = u_i2.release(); //释放所有权
unique_ptr<string> u_s(new string("abc"));
unique_ptr<string> u_s2 = std::move(u_s); //所有权转移(通过移动语义),u_s所有权转移后,变成“空指针”
u_s2.reset(u_s.release()); //所有权转移
u_s2=nullptr;//显式销毁所指对象,同时智能指针变为空指针。与u_s2.reset()等价
2. auto_ptr 和unique_ptr指针对比
auto_ptr是由C98引入,为实现和unique类似功能创建。但是auto_ptr指针在安全性方面存在缺陷,严格性不好。两个auto_ptr指针间可以赋值,这就导致指向同一个对象。在delete等操作过程中导致潜在的风险,导致出错。
例子:
#include <iostream>
#include <string>
#include <memory>
using namespace std;
int main() {
auto_ptr<string> films[5] ={
auto_ptr<string> (new string("Fowl Balls")),
auto_ptr<string> (new string("Duck Walks")),
auto_ptr<string> (new string("Chicken Runs")),
auto_ptr<string> (new string("Turkey Errors")),
auto_ptr<string> (new string("Goose Eggs"))
};
auto_ptr<string> pwin;
pwin = films[2]; // films[2] loses ownership. 将所有权从films[2]转让给pwin,此时films[2]不再引用该字符串从而变成空指针
cout << "The nominees for best avian baseballl film are\n";
for(int i = 0; i < 5; ++i) {
cout << *films[i] << endl;
}
cout << "The winner is " << *pwin << endl;
return 0;
}
例子将在调用films[2]时出错。
- auto_ptr具备拷贝语义,而unique_ptr只有移动语义std::move()。unique_ptr在转移所有权后不能再调用原有指针,因为其已经不指向任何对象。如果调用原有指针会导致内存报错。为了避免这种问题,在调用unique_ptr之前应该去判断其是否为空指针。
unique_ptr<string> a ;
if(a.get()!= nullptr)
{
}
- unique_ptr可作为临时右值,进行拷贝操作。但是这种操作本身没有意义,所以其没有禁止。
- unique_ptr指针可放在容器类内使用,auto_ptr不行。
-
vector<unique_ptr<int> > a{new int 0, new int 1} ;
- 管理动态数组
-
p是一个指向int[]数组的首地址,若p[0]代表了数组的首个数字,正常来说,指针是不能采用p[0]来对所指对象进行操作,所以这里相当于unique_ptr提供了对[]符号的重载。(个人理解)unique_ptr<int[]> p (new int[3]{1,2,3}); p[0] = 0;// 重载了operator[]
参考: