C++的unique_ptr::release

释放给调用方返回的存储指针的所有权,并将存储的指针值设置为nullptr。

使用 release接管unique_ptr存储的原始指针的所有权。 调用方负责返回的指针的删除。 unique-ptr设置为空的默认构造状态。 在调用到release后,您可以将兼容类型的另一个指针分配到unique_ptr。

实例:

// stl_release_unique.cpp
// Compile by using: cl /W4 /EHsc stl_release_unique.cpp
#include <iostream>
#include <memory>

struct Sample {
   int content_;
   Sample(int content) : content_(content) {
      std::cout << "Constructing Sample(" << content_ << ")" << std::endl;
   }
   ~Sample() {
      std::cout << "Deleting Sample(" << content_ << ")" << std::endl;
   }
};

void ReleaseUniquePointer() {
   // Use make_unique function when possible.  
   auto up1 = std::make_unique<Sample>(3);
   auto up2 = std::make_unique<Sample>(42);
   
   // Take over ownership from the unique_ptr up2 by using release
   auto ptr = up2.release();
   if (up2) {
      // This statement does not execute, because up2 is empty.
      std::cout << "up2 is not empty." << std::endl;
   }
   // We are now responsible for deletion of ptr.
   delete ptr;
   // up1 deletes its stored pointer when it goes out of scope.   
}

int main() {
   ReleaseUniquePointer();
}

运行结果:

Constructing Sample(3)
Constructing Sample(42)
Deleting Sample(42)
Deleting Sample(3)

注意一点:

release后被接管的指针ptr,需要自己释放;而原先的up1离开了函数自动释放。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值