空指针到对象问题 [英] Null Pointer to Object problems
问题描述
有人可能会告诉为什么在Linux和Windows中出现同样的问题:
#include< iostream>
using namespace std;
class A
{
private:
int _dmember;
public:
void func()
{
cout<<Inside A !!<< endl;
cout<< _dmember; //当到达这里时崩溃。
}
};
int main()
{
A * a = NULL;
a-> func(); // printsInside A !!!
return 1;
}
有人能告诉你为什么会出现这种奇怪的行为?我的意思是,
a-> func()不应该在func()里面,...?
这是不受欢迎的行为,
为什么会出现上述行为?
a * = null是intentionaly!所以对于所有回答这是未定义的行为或你应该永远不应该尝试调用一个NULL指针上的函数!,来了...这是点。这种行为是由你们中的一些人正确解释的。
永远不要在空指针上调用函数。 b
$ b
一些背景信息可能有用。在内部,函数不存储在对象中。相反,上面的代码(概念上)变成这样:
class A {
int _dmember;
};
void A :: func(A * this){
cout<< 里面A! << endl;
cout<< this-> _dmember< endl;
}
int main(){
A * a = ...;
A :: func(a);
}
所以,你看到没有什么实际阻止你调用函数空指针。但是,一旦该函数尝试访问类中的字段,通过无效的 this
指针,bang,你就死了。
Nitpicker的角落:虚拟功能是不同的故事。
Hi can someone tell why in Linux and windows the same problem occurs :
#include <iostream>
using namespace std;
class A
{
private:
int _dmember;
public:
void func()
{
cout<<"Inside A!! "<<endl;
cout<<_dmember; // crash when reach here.
}
};
int main ()
{
A* a= NULL;
a->func(); // prints "Inside A!!!"
return 1;
}
can someone tell why this weird behivior occurs ? i mean , the a->func() was not supposed to get inside the func() ,...? this is unwated behavior ,
why the above behivor occurs?
EDIT: Of course , a* =null was intentionaly!! so for all who answered "this is undefined behavior" or "you should never try to call a function on a NULL pointer !!", come on.... that was the point. and this behavior was explained correctly by some of you.
You must never, ever, call functions on a null pointer.
Some background information may be useful. Internally, the function is not stored "in" the object. Rather, the above code (conceptually) becomes something like this:
class A {
int _dmember;
};
void A::func(A *this) {
cout << "Inside A!!" << endl;
cout << this->_dmember << endl;
}
int main() {
A *a = ...;
A::func(a);
}
So, you see there is nothing that actually prevents you from calling a function on a null pointer. But as soon as that function tries to access a field inside the class, through the invalid this
pointer, bang, you're dead.
Nitpicker's corner: Virtual functions are a different story.
这篇关于空指针到对象问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!