Why does default constructor only work with class pointers?

Kai*_*kha 3 c++ oop default-constructor

I've been messing around with a default constructor example inspired by this answer. This one works fine:

class Foo {
public:
    int x;
    Foo() = default;
};

int main() {    
    for (int i = 0; i < 100; i++) {
        Foo* b = new Foo();
        std::cout << b->x << std::endl;
    }
Run Code Online (Sandbox Code Playgroud)

But when I try this out with a class instance on the stack it does not! For example, if I instantiate the class like Foo b I get an error saying uninitialised local variable 'b' used.

However, when I change the constructor to Foo() {}, instantiation with Foo b works fine, and I see random garbage from b.x as expected.

Why doesn't a default constructor work when I instantiate a class on the stack?

I compiled the code with MVSC C++17: 截屏

Ted*_*gmo 7

这是因为x未初始化。读取未初始化的变量会使您的程序具有未定义的行为,这意味着它可能随时停止“工作”。它也可能在幕后做一些奇怪的事情,而你认为​​一切都很好时却没有意识到。

这些都是零初始化x

Foo* b = new Foo();
Foo* b = new Foo{};
Foo b{};
Run Code Online (Sandbox Code Playgroud)

虽然这些没有:

Foo *b = new Foo;
Foo b;
Run Code Online (Sandbox Code Playgroud)

MSVC 可能不会捕获并警告您未初始化变量并稍后读取它的所有情况。不需要这样做 - 这就是为什么您可能会在一种情况下收到警告,但在另一种情况下不会收到警告。

  • 问题是太多新程序员使用程序的可观察行为来找出 C++ 规则。这不是解决问题的有效方法。C++ 的规则是在语言规则中定义的,而不是由程序的行为方式定义的。编译器的默认构造函数不会浪费时间*在优化的构建中*初始化您的成员变量——如果它这样做了,请准备好应对 C++ 社区将给编译器供应商带来的混乱。 (2认同)