下面的代码:
class A {
public:
void func(){}
void func1(){a = 0;}
private:
int a;
};
int main()
{
A* a = 0;
a->func();
a->func1();
}
我使用vs2008和g++ 4.8.2编译,调用func()
不会有问题,调用func1()
会出错
但有人说调用func()
也会出错(不知道是他确时出错,还是测试代码写的不一样导致出错)
所以我想知道空指针调用成员函数是未定义行为,由编译器决定如何做,还是C++标准有相关规定
The
this
of a member function can be a null pointer, as long asthis
is not used explicitly/implicitly in the member function. This is becausethis
in C++ is actually the last parameter of the function, nothing special, so there is no undefined behavior in it.This feature actually has no special use. I only use this feature a little in chain calls of certain pointers.
For example:
bar
andplay
are both functions that returnFoo *
, so if you writeif (!this) return nullptr;
inside, you can easily implement chain calls without checking the return value.Of course it is Undefined behavior. Just when you thought it was not wrong, it has quietly contacted the Trisolarans and given them the coordinates of the sophons.
Closer to home, the so-called UB means that no one can predict and be responsible for the consequences of this type of behavior. It may work normally under certain circumstances, but there is no guarantee.
I guess that as long as member variables, virtual functions and other things that require object addresses are not used, there should be no problem in calling that function. . . It's just that when the function is called, the register of this pointer is 0. .
It also depends on the platform. Linux will definitely make mistakes. Unix usually has no problems, but there is no guarantee
I will help you translate it into pure C code for you to take a look
Then understand it yourself. Virtual without using C++ is almost like this. If some of the people above don’t move, don’t answer.