unique_ptr 为独占的智能指针,与所指对象的内存绑定紧密,不能与其他unique_ptr类型的指针对象共享所指对象的内存。比如
unique_ptr<TEST> p1(new TEST("case_1"));
auto p44 = p1;
编译是不能通过的。可以通过move来转移内存
unique_ptr<TEST> p1(new TEST("case_1"));
auto p44 = move(p1);
断点调试一下
继续往下
我们可以发现 p44指向的地址变成了p1开始指向的地址,而p1的地址变成了0x0.
另外通过release函数也可以实现转移
*************************内存又是如何释放的呢?*********************
举个例子
class TEST
{
public:
TEST(const string & name)
:_name(name)
{
cout<<"TEST:"<<_name<<endl;}
~TEST()
{
cout<<"~TEST:"<<_name<<endl;
}
//private:
string _name;
};
int main()
{
unique_ptr<TEST> p1(new TEST("case_1"));
unique_ptr<TEST> p2(p1.release()); //!将所有权从p1转移到p2,p1现在指向NULL。
cout<<"++++++++++++++++++++++++"<<endl;
unique_ptr<TEST> p3(new TEST("case_2"));
p2.reset(p3.release()); //!p2释放了原来指向的内存,接受了p3指向的内存。
return 0;
}
输出结果如下:
case1被自动释放了,应为p2被赋予了其他值。