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

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

发布时间:2020-12-16 03:11:19 所属栏目:百科 来源:网络整理
导读:考虑这个代码: class Addressable;class Class1 { void foo(Addressable a) { (void) a; } }; // OKclass Addressable { void *operator () { return this; } };class Class2 { void foo(Addressable a) { (void) a; } }; // Error: operator private 为什
考虑这个代码:
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允许使用不完整的参考类型的地址?

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

解决方法

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

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

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

报价N4140:

5.3.1 Unary operators [expr.unary.op]

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.

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

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并接受它.

(编辑:李大同)

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

    推荐文章
      热点阅读