Why am I able to make a function call using an invalid class pointer(为什么我可以使用无效的类指针进行函数调用)
问题描述
在下面的代码片段中,虽然指针没有初始化,但调用仍然成功
In below code snippet, although pointer is not initialized the call is still made successfully
temp *ptr;
ptr->func2();
是C++语言属性的问题,还是VC++6编译器玩坏了?
Is it due to C++ language property, or it is VC++6 compiler which is foul playing?
class temp {
public:
temp():a(9){}
int& func1()
{
return a;
}
bool func2(int arg)
{
if(arg%2==0)
return true;
return false;
}
int a;
};
int main(int argc, char **argv)
{
temp *ptr;
int a;
cin>>a;
if(ptr->func2(a))
{
cout<<"Good poniner"<<endl;
}
ptr->func1(); // Does not crash here
int crashere=ptr->func1();// But does crash here
return 0;
}
推荐答案
C++ 编译器不会阻止您使用未初始化的指针,虽然结果未定义,但现实世界中的编译器生成忽略的代码是正常的指针未初始化的事实.
The C++ compiler doesn't prevent you from using uninitialised pointers, and although the results are undefined, it's normal for compilers in the real world to generate code that ignores the fact that the pointer is uninitialised.
这是 C++ 相对于其他一些语言既快速又(相对)危险的原因之一.
It's one of the reasons why C++ is both fast and (comparatively) dangerous relative to some other languages.
您对 func2 的调用成功的原因是它没有触及它的 this 指针.指针值从未使用过,因此不会引起问题.在 func1 你do 使用 this 指针(访问成员变量),这就是它崩溃的原因.
The reason your call to func2 succeeds is that it doesn't touch its this pointer. The pointer value is never used, so it can't cause a problem. In func1 you do use the this pointer (to access a member variable), which is why that one crashes.
这篇关于为什么我可以使用无效的类指针进行函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我可以使用无效的类指针进行函数调用
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
