unique_ptr::release
释放给调用方返回的存储指针的所有权,并将存储的指针值设置为nullptr。
pointer release();
属性值/返回值
返回存储的指针。
备注
使用 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();
}
计算机输出:
要求
标头: <memory>
命名空间: std