加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

将成员函数指针与0进行比较总是有效的吗?

发布时间:2020-12-16 10:28:35 所属栏目:百科 来源:网络整理
导读:在下面的代码中,使用Visual Studio编译器不会引发断言,但是在使用XCode为iPhone编译时会引发该断言: class X{public: virtual void A() {}};X x;void main(){ // Define a valid member function pointer to X::A. void (X::*p)() = X::A; assert(p != 0);}
在下面的代码中,使用Visual Studio编译器不会引发断言,但是在使用XCode为iPhone编译时会引发该断言:

class X
{
public:

 virtual void A() {}
};

X x;

void main()
{
 // Define a valid member function pointer to X::A.
 void (X::*p)() = &X::A;

 assert(p != 0);
}

这是编译器中的错误吗?在这种情况下,如何检查空指针呢?

解决方法

代码是正确的,编译器不符合标准,它表示(section [expr.eq],使用C 0x草案n3225中的措辞,但在其他版本中它应该是相同的):

any pointer to member can be compared to a null pointer constant

If both operands are null,they compare equal. Otherwise if only one is null,they compare unequal.

空指针常量的相关定义(section [conv.ptr],std :: nullptr_t部分在C 0x中是新的):

A null pointer constant is an integral constant expression (5.19) prvalue of integer type that evaluates to zero or a prvalue of type std::nullptr_t.

和(section [expr.const]):

A constant expression is an integral constant expression if it is of integral or enumeration type.

注意:另外,指向虚拟成员函数的指针的实现定义表示通常是虚拟表的索引,在问题中为0.但是根据标准,断言内部的表达式不检查表示是否为零,它是否检查零文字 – 它是一个空指针检查.

Apple编译器显然混淆了两者.如果你想测试表示是否为零,你可以编写assert((intptr_t)p!= 0) – 这将是完全不可移植的.

但是编写的代码对任何符合标准的编译器都是完全可移植的,并且永远不会断言.

编辑:还有一个来自标准的引用,它重复了我们已经学过的内容(第[conv.mem]节):

A null pointer constant (4.10) can be converted to a pointer to member type; the result is the null member pointer value of that type and is distinguishable from any pointer to member not created from a null pointer constant.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读