在没有对象初始化的情况下调用 C++ 函数

2022-01-18 00:00:00 object initialization pointers c++

为什么下面的代码会运行?

Why does the following code run?

#include <iostream>
class A {
    int num;
    public:
        void foo(){ num=5; std::cout<< "num="; std::cout<<num;}
};

int main() {
    A* a;
    a->foo();
    return 0;
}

输出是

num=5

我使用 gcc 编译它,我在第 10 行只收到以下编译器警告:

I compile this using gcc and I get only the following compiler warning at line 10:

(警告:a"在此函数中未初始化)

但根据我的理解,这段代码不应该根本不运行吗?为什么在 num 不存在时将值 5 分配给 num 因为还没有创建 A 类型的对象?

But as per my understanding, shouldn't this code not run at all? And how come it's assigning the value 5 to num when num doesn't exist because no object of type A has been created yet?

推荐答案

你还没有初始化*a.

试试这个:

#include <iostream>

class A
{
    int num;
    public:
        void foo(){ std::cout<< "num="; num=5; std::cout<<num;}
};

int main()
{
    A* a = new A();
    a->foo();
    return 0;
}

<小时>

未(正确)初始化指针会导致未定义的行为.如果幸运的话,您的指针会指向堆中的一个位置,该位置已准备好进行初始化*.(假设您执行此操作时没有引发异常.)如果您不走运,您将覆盖用于其他目的的一部分内存.如果你真的很倒霉,这将被忽视.


Not initializing pointers (properly) can lead to undefined behavior. If you're lucky, your pointer points to a location in the heap which is up for initialization*. (Assuming no exception is thrown when you do this.) If you're unlucky, you'll overwrite a portion of the memory being used for other purposes. If you're really unlucky, this will go unnoticed.

这不是安全代码;黑客"可能会利用它.

This is not safe code; a "hacker" could probably exploit it.

*当然,即使您访问该位置,也不能保证以后不会初始化".

*Of course, even when you access that location, there's no guarantee it won't be "initialized" later.

幸运"(实际上,幸运"会让你的程序更难调试):

"Lucky" (actually, being "lucky" makes it more difficult to debug your program):

// uninitialized memory 0x00000042 to 0x0000004B
A* a;
// a = 0x00000042;
*a = "lalalalala";
// "Nothing" happens

<小时>

倒霉"(让调试程序更容易,所以我不认为它倒霉",真的):


"Unlucky" (makes it easier to debug your program, so I don't consider it "unlucky", really):

void* a;
// a = &main;
*a = "lalalalala";
// Not good. *Might* cause a crash.
// Perhaps someone can tell me exactly what'll happen?

相关文章