c++ - Why are we allowed to take the address of an incomplete type? -
consider code:
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 why c++ allow taking address of incomplete reference type?
couldn't potentially illegal, shown above? intentional?
yes, that's intentional, , possibility of breakage if operator& overloaded known.
taking address of incomplete types has been possible since long before c++. in c, there absolutely no risk of breakage, because & cannot overloaded.
c++ chose not unnecessarily break valid programs, , specified if incomplete type turn out have overloaded & operator, it's unspecified whether overloaded operator gets used.
quoting n4140:
5.3.1 unary operators [expr.unary.op]
if
&applied lvalue of incomplete class type , complete type declaresoperator&(), unspecified whether operator has built-in meaning or operator function called.
this can interpreted apply class being declared, , when declaration of operator& has been seen:
extern struct a; struct {   int operator&();   decltype(&a) m; // int, or *? }; int main() {   return a().m; // valid if m int } here, gcc gives m type a * , rejects program, clang gives type int , accepts it.
Comments
Post a Comment