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