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
如上图所示,它不可能是非法的吗?这是有意的吗?
解决方法 是的,这是有意的,如果运算符和被超载是已知的.早在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 declaresoperator&()
,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并接受它.
总结以上是内存溢出为你收集整理的c – 为什么我们允许使用不完整类型的地址?全部内容,希望文章能够帮你解决c – 为什么我们允许使用不完整类型的地址?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)