uniqut_ptr是一种对资源具有排他性拥有权的智能指针,即一个对象资源只能同时被一个unique_ptr指向。
通过new云算法或者普通指针
unique_ptr<Investment> up(new Investment());
或者
Investment *pInv = new Investment();
unique_ptr<Investment> up1(pInv);
通过make_unique
auto pInv = make_unique<Investment>();
通过move()函数
unique_ptr<Investment> up1 = std::move(up);
注意:unique_ptr不能被复制或者拷贝,下面的代码将出错:
unique_ptr<Investment> up(new Investment()); //ok
unique_ptr<Investment> up1(up); //error, can not be copy
unique_ptr<Investment> up2 = up; //error, can not be assigned
但是,unique_ptr可以作为函数的返回值:
unique_ptr<Investment> GetPtr(); //function getthe unique pointer
unique_ptr<Investment> pInv = GetPtr(); // ok
用如下方式使用带自定义资源释放的unique_ptr
auto delete_Investment = [](Investment* pInv)
{
pInv->getObjectType();
delete pInv;
};
unique_ptr<Investment,decltype(delete_Investment)> pInvest(nullptr,delete_Investment);
或者也可以使用函数指针
void deleteInv(Investment* pInv) {}
std::unique_ptr<Investment,void(*)(Investment*)>ptr(nullptr,deleteInv) ;
class CConnnect
{
void Disconnect() { PRINT_FUN(); }
};
void Deleter(CConnnect* obj)
{
obj->Disconnect(); // 做其它释放或断开连接等工作
delete obj; // 删除对象指针
}
std::unique_ptr up(new CConnnect, Deleter);
class Deleter
{
public:
void operator() (CConnnect* obj)
{
PRINT_FUN();
delete obj;
}
};
std::unique_ptr up1(new CConnnect);
std::unique_ptr up2(new CConnnect, up1.get_deleter());
unique_ptr<Investment> pInvestment; // 创建一个空的智能指针
pInvestment.reset(new Investment()); //"绑定”动态对象
Investment *pI = pInvestment.release(); //释放所有权
pI= nullptr; //显式销毁所指对象,同时智能指针变为空指针。
由于unique_ptr有std::unique_ptr
unique_ptr<int[]> pArray(new int[3]{1,3,3});