如何重新赋值(即设置)类型为unique_ptr的类成员?
在C++中给类的unique_ptr成员重新赋值的方法
嘿,这个问题在C++开发里挺常见的,我来给你拆解几种靠谱的做法,都是日常开发中常用的:
1. 直接赋值std::make_unique创建的对象
这是最简洁也最推荐的方式,make_unique会自动分配内存并返回一个unique_ptr,赋值时会自动转移所有权,同时销毁原来unique_ptr持有的资源。
举个类的示例:
#include <memory> class MyClass { private: std::unique_ptr<int> my_ptr_; // 类的unique_ptr成员 public: void set_new_value(int val) { // 直接赋值,旧资源会被自动释放 my_ptr_ = std::make_unique<int>(val); } };
2. 使用reset()方法
reset()是unique_ptr的成员函数,专门用来重置指针:
- 传入新的裸指针:
ptr_.reset(new int(42));(不过尽量少用裸指针,优先make_unique) - 传入
std::make_unique的结果(更安全):ptr_.reset(std::make_unique<int>(42).release()); - 不传参数:
ptr_.reset();会直接释放当前资源,将指针置为空
示例代码:
void reset_my_ptr(int val) { // 推荐的reset写法,避免裸指针 my_ptr_.reset(std::make_unique<int>(val).release()); // 或者简单点直接用赋值,效果一样 // my_ptr_ = std::make_unique<int>(val); } void clear_my_ptr() { my_ptr_.reset(); // 清空指针,释放资源 }
3. 转移另一个unique_ptr的所有权
如果你有另一个unique_ptr想把所有权转移给类的成员,需要用std::move()来触发移动语义,因为unique_ptr是独占所有权的,不能直接复制。
示例:
void take_ownership(std::unique_ptr<int>&& external_ptr) { // 用std::move转移所有权,external_ptr会后变成空指针 my_ptr_ = std::move(external_ptr); } // 调用方式: // std::unique_ptr<int> external = std::make_unique<int>(100); // my_class.take_ownership(std::move(external));
几个关键注意事项
- 禁止直接复制
unique_ptr:因为它的设计就是独占所有权,所以不能做my_ptr_ = another_unique_ptr;,必须用std::move() - 自动资源管理:无论用哪种方式赋值,原来
unique_ptr持有的资源都会被自动释放,不需要手动调用delete - 清空指针:如果只是想清空成员变量,直接
my_ptr_ = nullptr;或者my_ptr_.reset();都可以,效果完全一致
内容的提问来源于stack exchange,提问作者code
相关产品推荐
相关产品推荐

