问题描述
在下面的代码片段中,虽然指针没有初始化,但调用仍然成功
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.
这篇关于为什么我可以使用无效的类指针进行函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)