gpt4 book ai didi

c++ - 自动变量初始化和复制/移动构造函数

转载 作者:太空狗 更新时间:2023-10-29 20:02:42 25 4
gpt4 key购买 nike

我有一个片段:

struct MyCass2 {
MyCass2() {}

MyCass2(MyCass2 const&) = delete;

MyCass2(MyCass2&&) = delete;
};

int
main() {
auto a = MyCass2();
}

这导致

main.cpp:43:8: error: call to deleted constructor of 'MyCass2'
auto a = MyCass2();
^ ~~~~~~~~~
main.cpp:38:3: note: 'MyCass2' has been explicitly marked deleted here
MyCass2(MyCass2&&) = delete;
^
1 error generated.

为什么我认为毕竟会有模板类型推导和直接初始化?有人可以解释一下在这种情况下自动变量初始化是如何工作的吗?

最佳答案

Why I thought there will be a template type deduction

auto 使用模板参数推导规则推导变量的类型。在这种情况下,类型将被推断为 MyCass2

and a direct initialization after all?

a 不是 direct-initialized ,因为你使用了 copy-initialization - 请参阅标记为 (1) 的语法。

how the automatic variable initialization work in this case?

a 是从 = 右侧的临时变量复制初始化的。但是,由于该类型既不可复制也不可移动,因此不允许进行复制初始化。

But I [defined] the move/copy constructors and neither of them was called, how is that?

默认构造函数用于初始化临时对象。复制初始化中对移动构造函数的调用允许为elided .

I was sure that this auto var=initializer is kind of a syntax overloading. Like with copy initialization T var=initializer, where instead of operator= a copy constructor is called.

嗯,事实并非如此。这里,auto 用于且仅用于推断类型。一旦推断出类型,表达式就完全等同于

MyCass2 a = MyCass2();

关于c++ - 自动变量初始化和复制/移动构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37162095/

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