gpt4 book ai didi

c++ - 现代 C++ 中的默认构造函数

转载 作者:太空宇宙 更新时间:2023-11-04 12:51:59 25 4
gpt4 key购买 nike

当我运行这段代码时,VS 编译器返回错误并指出 t1.mem 是未初始化的局部变量。

#include <string>
#include <iostream>
struct T1
{
int mem;
};

struct T2
{
int mem;
T2() { } // "mem" is not in the initializer list
};


int main()
{

T1 t1; // class, calls implicit default ctor
std::cout << t1.mem << std::endl;
const T2 t2; // const class, calls the user-provided default ctor
// t2.mem is default-initialized (to indeterminate value)
std::cout << t2.mem << std::endl;

}

如果我没有为 struct T1 分配构造函数,编译器是否必须生成默认构造函数?而struct T2的构造函数是空的初始化列表,为什么没有错误提示?

最佳答案

我的理解是,编译器试图保护您免受其自己生成的代码的影响,并在使用您提供的构造函数时假定“您最了解”。此外,检查您的构造函数是否实际上在任何地方(包括在构造函数的主体中)初始化 T2.mem 可能是一项任意复杂的任务,因此编译器作者可能已经决定这是一个任务未尝试总比执行不当好。

这似乎得到了 warning you would get 的支持如果您将 t1 声明为 const T1,则来自 MSVC:

'const' automatic data initialized with compiler generated default constructor produces unreliable results

注意“编译器生成默认构造函数”这句话。

顺便说一句,如果您使用 T2() = default 请求编译器生成的默认构造函数,您会看到同样的警告。

关于c++ - 现代 C++ 中的默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48676863/

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