gpt4 book ai didi

c++ - 使用值初始化访问构造函数?

转载 作者:行者123 更新时间:2023-11-30 01:36:16 24 4
gpt4 key购买 nike

所以根据this article ,符号 A()new A() 导致值初始化。据我了解,这两种表示法都应转换为默认初始化

for if T is a class type with no default constructor or with a user-provided or deleted default constructor, the object is default-initialized;

他们应该从中引起相同的行为。那么,为什么会这样:

class Image
{
public:
Image();
virtual ~Image();

protected:
std::string _filePath;

protected:
// noncopyable
Image(const Image& rImg);
Image& operator=(const Image&);
bool initWithImageFileThreadSafe(const std::string& fullpath);

};

int main()
{
auto a = new Image(); //Works
auto aa = Image(); //Error: inaccessible constructor
}

最佳答案

当你做的时候

auto a = new Image(); //Works

您动态创建了一个 Image 并且 a 被初始化为一个指向它的指针。这很好,因为它是 Image 的直接初始化。

当你做的时候

auto aa = Image(); //Error: inaccessible constructor

在 C++17 之前,您调用复制初始化,它使用值初始化的临时 Image 作为初始化 aa 的值。因为你的复制构造函数被标记为 protected 这实际上是不允许发生的,你会得到一个编译器错误。即使可以省略此拷贝,您仍然需要一个可访问的复制/移动构造函数。

在 C++17 之后,这里实际上没有生成临时文件,编译器基本上将代码转换为 Image aa{};,这样拷贝就被省略了,不需要可访问的拷贝/移动构造函数。

关于c++ - 使用值初始化访问构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52505119/

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