为什么通过空指针“工作”调用方法?在C ++中? [英] Why does calling method through null pointer "work" in C++?

查看:59
本文介绍了为什么通过空指针“工作”调用方法?在C ++中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

通过NULL类指针调用类方法





#include <iostream>
using namespace std;
class test
{
    int i;
public:
    test():i(0){ cout << "ctor called" << endl;}
    void show()
    {
        cout<<"show fun called"<<endl;
    }
};

int main(int argc , char *argv[])
{
    test *ptr = NULL;
    ptr->show();
    return 0;
}

显然,不会调用任何ctor。这是标准吗?还是只是一些编译器优化,因为show()成员函数中未使用此指针?

clearly, no ctor will be called. Is this standard? or just some compiler optimization as this pointer is not used in show() member function?

推荐答案

不需要该指针调用方法。指针的类型是已知的,因此该方法的代码也是已知的。该方法不使用 this ,因此可以正常运行代码。这是未定义的行为,但更有效的方法是不检查指针是否为NULL,以便运行。

The pointer isn't needed to call the method. The type of the pointer is known, so the code for the method is known. The method doesn't use this, so it runs the code just fine. It's undefined behavior, but its more efficient not to check if the pointer is NULL, so it runs.

这篇关于为什么通过空指针“工作”调用方法?在C ++中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆