C++用空指针调用成员函数是未定义行为吗?
高洛峰
高洛峰 2017-04-17 11:27:04
0
5
701

下面的代码:

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++标准有相关规定

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(5)
左手右手慢动作

The this of a member function can be a null pointer, as long as this is not used explicitly/implicitly in the member function. This is because this 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:

Foo *foo = ...;
foo->bar()->play();

bar and play are both functions that return Foo *, so if you write if (!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. .

PHPzhong

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

struct A{
    int a;
};

void fun(A* this)
{
}

void func1(A* this)
{
    this->a = 0;  // <--- 这里当然有问题啦
}

int main()
{
    A* a = 0;
    fun(a);
    fun1(a);
}

Then understand it yourself. Virtual without using C++ is almost like this. If some of the people above don’t move, don’t answer.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template