是否合法的C ++在成员函数中测试this指针? [英] Is it legal C++ to test the this-pointer in a member function?

查看:119
本文介绍了是否合法的C ++在成员函数中测试this指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个涉及不同类型对象的应用程序。对象由指针引用。空指针表示关联的对象不存在。目前调用代码很繁琐,因为每次使用指向对象的指针时,它会测试指针值为null,并采取一些适当的操作为null。因为在不存在的情况下采取的默认动作取决于对象的类型,我宁愿将其编码在对象本身的类中,而不是在调用程序中。这导致如下的构造:

I have an application involving objects of different class types. The objects are referenced by pointers. A null pointer signifies that the associated object does not exist. Currently the calling codes is cumbersome, because each time it uses a pointer to an object, it tests the pointer value for null, and take some appropriate action it is null. Because the default action to be taken in the case of non-existence depends on the type of object, I would prefer to encode it in the classes for the objects themselves rather than in the calling program. This results in constructions like the following:

class C
{ ... 
  void member_func() //non-virtual !
  { if (this) { do something with the object ... }
    else { take some default action }
  }
  ...
};

很明显,成员函数不能是虚拟的,因为当对象不存在时,查找表不存在,并且虚拟调用将失败。但是这个代码是非虚拟成员函数的合法C ++吗?它似乎工作正确的编译器我试过它,但我担心可能的不可移植性。在标准中,我找不到明确允许或明确禁止此类构造的子句。

Clearly the member function cannot be virtual, because the lookup table does not exist when the object does not exist, and the virtual call would fail. But is this code legal C++ for non-virtual member functions? It seems to work correctly for the compilers I have tried it on, but I am worried about possible non-portability. In the standard I can’t find a clause that either expressly allows or expressly prohibits such constructions.

推荐答案

在成员函数中永远不会为null,因此您执行的检查是无用的。

this will never be null in a member function so the check you perform is useless.

如Matthieu M.在注释中指出,如果您在代码中执行这样的操作:

As pointed by Matthieu M. in a comment, if you do something like this in your code:

C* c = 0; 
c->member();

这会导致未定义的行为,这是

这篇关于是否合法的C ++在成员函数中测试this指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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