c – 为什么我们允许使用不完整类型的地址?

前端之家收集整理的这篇文章主要介绍了c – 为什么我们允许使用不完整类型的地址?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
考虑这个代码
class Addressable;
class Class1  { void foo(Addressable &a) { (void) &a; } };  // OK
class Addressable { void *operator &() { return this; } };
class Class2  { void foo(Addressable &a) { (void) &a; } };  // Error: operator & private

为什么C允许使用不完整的参考类型的地址?@H_403_5@

如上图所示,它不可能是非法的吗?这是有意的吗?@H_403_5@

解决方法

是的,这是有意的,如果运算符和被超载是已知的.

早在C之前就已经有了不完整的地址.在C中,绝对没有任何破损的风险,因为&不能超载.@H_403_5@

C选择不会不必要地破坏以前有效的程序,并且简单地指出,如果一个不完整的类型确实有一个超载&运算符,是否重载运算符被使用是未指定的.@H_403_5@

报价N4140:@H_403_5@

5.3.1 Unary operators [expr.unary.op]@H_403_5@

If & is applied to an lvalue of incomplete class type and the complete type declares operator&(),it is unspecified whether the operator has the built-in meaning or the operator function is called.@H_403_5@

这可以解释为甚至应用于当前正在声明的课程,甚至在操作符&已经看到:@H_403_5@

extern struct A a;
struct A {
  int operator&();
  decltype(&a) m; // int,or A *?
};
int main() {
  return A().m; // only valid if m is int
}

在这里,GCC给出A型*,并拒绝该程序,但是clang给它类型int并接受它.@H_403_5@

猜你在找的C&C++相关文章