如何重新分配(也称为集合)unique_ptr类成员?
How can you re-assign (a.k.a set) class member that is unique_ptr?
class A {};
class B{
unique_ptr<A> upA;
public:
B() : upA(make_unique<A>()) {}
void set(A a){
upA.reset(move(a)); //error
//upA.reset(a); //error
//upA = move(a); //error
}
};
如何重新分配(也称为集合)unique_ptr类成员?
这取决于你想做什么。是否要在upA
管理的对象上调用operator=
?㞖:
*upA = a;
您想接受新unique_ptr
并拥有它吗?㞖:
void set(std::unique_ptr<A> a){
upA = move(a);
}
unique_ptr<A> upA;
所以这是一个独特的(智能)指针,指向位于某处的 A - 到目前为止还不错。
B() : upA(make_unique<A>()) {}
好的,我们初始化指针以指向一个新的、动态分配的A
- 看起来很合理。
void set(A a){
upA.reset(move(a));
但是现在您想将智能指针(负责管理它指向的对象的生存期)指向 A 的本地实例?这没有意义,原因有两个:
- 智能指针管理指针,并且您正在向其传递一个本地对象(左值引用)。您可以通过编写
&a
将其转换为指针,但这仍然存在以下问题: - 当函数返回时,您的局部变量
a
将超出范围,使您的智能指针具有悬而未决的无效地址,需要尝试管理。
当你打电话给B::set
,应该发生什么?您需要从调用方的角度决定它打算做什么。也:
// transfer control of the caller's A to B
void B::set(std::unique_ptr<A> a) { upA = move(a); }
或
// take control of the caller's allocated but unmanaged A
void B::set(A *a) { upA.reset(a); }
// not recommended - keep everything managed by unique_ptr if at all possible
或
// copy the caller's A into B's existing A
void B::set(A const &a) { *upA = a; }
// called as
b.set(my_local_a);
或
// move the caller's temporary A into B's existing A
void B::set(A &&a) { *upA = move(a); }
// called with an explicit move
b.set(move(my_local_a));
// or with a prvalue
b.set(A{});
相关文章:
- 为什么 std::unique 不调用 std::sort?
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 生成"unique"矩阵
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 我对 std::unique(算法)C++有问题
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- std::shared_ptr::unique(),复制和线程安全
- 如何在C++03中用自定义谓词调用std::unique
- C++中的指针否定 (!ptr == NULL)
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误