[英]Why does unary operator & not require a complete type?
The following code compiles fine with both gcc 7.2.0 and clang 6.0.0 . 以下代码使用gcc 7.2.0和clang 6.0.0编译得很好。
#include <iostream>
struct stru;
void func(stru& s) {
std::cout << &s << std::endl;
}
int main() {
}
I'm wondering how this is OK. 我想知道这是怎么回事。 What if
stru
has overloaded operator&()
? 如果
stru
重载operator&()
会怎么样? The compiler should not be able to tell with simply a forward declaration like struct stru
. 编译器不应该简单地告诉像
struct stru
这样的前向声明。 In my opinion, only std::addressof(s)
is OK with an incomplete type. 在我看来,只有
std::addressof(s)
可以使用不完整的类型。
What if
stru
has overloadedoperator&()
?如果
stru
重载operator&()
会怎么样?
Then it is unspecified whether the overload will be called (See Oliv's comment for standard quote). 然后未指定是否将调用重载(参见Oliv对标准引用的注释)。
How could unary operator & does not require a complete type?
一元操作员怎么可能并不需要完整的类型?
That's how the standard has defined the language. 这就是标准定义语言的方式。 The built-in address-of operator doesn't need to know the definition of the type, since that has no effect on where to get the address of the object.
内置的address-of运算符不需要知道类型的定义,因为这对获取对象地址的位置没有影响。
One consideration for why it is a good thing: Compatibility with C. 一个考虑为什么它是一件好事:与C的兼容性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.