成员初始化列表中的unique_ptr
unique_ptr in member initialization list
编辑:我知道unique_ptr是不可复制的,只能移动。我不明白初始化列表会发生什么。
为什么成员初始化列表中的unique_ptr可以像代码片段中那样工作?
#include <memory>
class MyObject
{
public:
MyObject() : ptr(new int) // this works.
MyObject() : ptr(std::unique_ptr<int>(new int))
// i found this in many examples. but why this also work?
// i think this is using copy constructor as the bottom.
{
}
MyObject(MyObject&& other) : ptr(std::move(other.ptr))
{
}
MyObject& operator=(MyObject&& other)
{
ptr = std::move(other.ptr);
return *this;
}
private:
std::unique_ptr<int> ptr;
};
int main() {
MyObject o;
std::unique_ptr<int> ptr (new int);
// compile error, of course, since copy constructor is not allowed.
// but what is happening with member initialization list in above?
std::unique_ptr<int> ptr2(ptr);
}
这与命名的和未命名的对象有关。
当你这样做时:
std::unique_ptr<int> ptr(new int);
// ^^^--- name is 'ptr'
但当你这样做时:
std::unique_ptr<int>(new int);
// ^--where is the name??
如果创建的对象没有名称,则称为临时或r值,并且编译器对r值的规则与对命名对象和l-values的规则不同。
命名对象(l-values(只能复制到另一个对象,但未命名对象(r-values(可以拷贝或移动。
在您的示例中,您使用std::unique_ptr
。这些对象只能移动,因为它们的复制语义已被禁用。这就是为什么当您尝试复制一个时,编译器会给出错误:
std::unique_ptr<int> ptr (new int);
// compile error, copy constructor delete
std::unique_ptr<int> ptr2(ptr); // copy is disabled!!
这里ptr
是一个命名对象,因此它只能被复制但其复制语义被禁用,因此整个操作是非法的。
但是当你对未命名的对象做类似的事情时,比如:
MyObject() : ptr(std::unique_ptr<int>(new int))
^--- look no name!!!
然后编译器可以复制或移动,并且它总是在尝试拷贝之前尝试移动。
std::unique_ptr
完全移动抱怨,因此编译器没有抱怨。
在您的示例中,std::unique_ptr<int>(new int)
是一个右值,因此使用了ptr
的move构造函数。
第二次(在main
中(,std::unique_ptr<int> ptr2(ptr)
不起作用,因为ptr
是一个左值,不能直接移动(可以使用std::move
(。
MyObject() : ptr(std::unique_ptr<int>(new int))
其使用CCD_ 10的移动构造函数(来自临时(。
您可以将main
更改为
std::unique_ptr<int> ptr2(std::move(ptr));
编译
相关文章:
- 为什么 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错误