Dereferncing NULL pointer to member function of class
This question already has an answer here:
Dereferencing a null pointer yields Undefined Behaviour.
I can guess why this still works for you (but again it's UB!), but if you try to access a member variable in func()
I'm pretty sure it will stop working.
Dereferencing a NULL
pointer means that you have undefined behavior.
However in this case on most implementations you will end up in correct function with this
being NULL
, the normal implementation of calling a non-virtual method is to set the hidden parameter this
as being the pointer to the object (in this case NULL
) and then just call the function. If you don't access member variables or call virtual methods you should be fine in most implementations.
Since you can't access members or call virtual functions or in any other way do anything useful with this
pointer you're pretty close to the scenario of a static
method and I'll suggest one use that instead if the this
pointer is not used.
For the corner case where you want to be able to do nothing else with the this
pointer than check for NULL
ness you could still use a static
method and explicitely pass the pointer to the object:
static void func(foo* diz) {
cout << "In func" << endl;
if( diz != NULL ) {
diz->actual_work_on_diz();
}
}
链接地址: http://www.djcxy.com/p/49710.html
上一篇: (gdb)在fd 0上检测到异常情况
下一篇: 取消对类的成员函数的NULL指针