C ++函数调用无对象初始化 [英] C++ function called without object initialization
问题描述
为什么会运行以下代码?
#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
在第10行只获取以下编译器警告:
( 警告:a在此函数中未初始化 >)
但是根据我的理解,这个代码不应该运行吗?当num不存在,因为没有创建类型A的对象时,如何将值5分配给num?
您尚未初始化 * 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;
}
未初始化指针)可能导致未定义的行为。如果你幸运的话,你的指针指向堆中的一个位置,用于初始化*。 (假设没有异常被抛出,当你这样做)。如果你不幸运,你会覆盖内存的一部分用于其他目的。
这是不安全的代码;一个黑客可能会利用它。
*当然,即使你访问该位置,也不能保证以后不会被初始化 p>
Lucky(实际上,lucky使您更难调试程序):
//未初始化的内存0x00000042到0x0000004B
A * a;
// a = 0x00000042;
* a =lalalalala;
//无发生
Unlucky(让你更容易调试你的程序,所以我不认为它不幸,真的):
void * a;
// a =& main;
* a =lalalalala;
//不好。 *可能*导致崩溃。
//也许有人可以告诉我到底会发生什么?
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;
}
The output is
num=5
I compile this using gcc and I get only the following compiler warning at line 10:
(warning: 'a' is used uninitialized in this function)
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?
You haven't initialized *a
.
Try this:
#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 ++函数调用无对象初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!