C++ function called without object initialization(在没有对象初始化的情况下调用 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?
这篇关于在没有对象初始化的情况下调用 C++ 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在没有对象初始化的情况下调用 C++ 函数
基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01