在下面的代码片段中,虽然指针没有初始化,但调用仍然成功
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模板网!
std::reference_wrapper 和简单指针的区别?Difference between std::reference_wrapper and simple pointer?(std::reference_wrapper 和简单指针的区别?)
常量之间的区别.指针和引用?Difference between const. pointer and reference?(常量之间的区别.指针和引用?)
c++ - 如何从指向向量的指针访问向量的内容?How to access the contents of a vector from a pointer to the vector in C++?(c++ - 如何从指向向量的指针访问向量的内容?)
*& 的含义和**&在 C++ 中Meaning of *amp; and **amp; in C++(*amp; 的含义和**amp;在 C++ 中)
为什么我不能对普通变量进行多态?Why can#39;t I do polymorphism with normal variables?(为什么我不能对普通变量进行多态?)
取消引用已删除的指针总是会导致访问冲突?Dereferencing deleted pointers always result in an Access Violation?(取消引用已删除的指针总是会导致访问冲突?)