gpt4 book ai didi

c++ - 成员初始化列表中的 unique_ptr

转载 作者:可可西里 更新时间:2023-11-01 18:16:58 25 4
gpt4 key购买 nike

编辑:我知道 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 值 有不同的规则em> 比它对命名对象l-values 的作用要大。

命名对象(l-values)只能复制到另一个对象,但未命名对象(r-values)可以是< em>复制 或移动

在您的示例中,您使用了 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 完全是移动投诉,因此编译器没有任何投诉。

关于c++ - 成员初始化列表中的 unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38985127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com