在 C++ 中将未命名临时变量括起来
考虑以下代码:
struct Foo
{
};
struct Bar
{
explicit Bar(const Foo&)
{
}
};
int main()
{
Foo foo;
Bar bar(foo); // Okay.
Bar(foo); // Will not compile.
(Bar(foo)); // Okay. Unnamed temporary requires parenthesis.
}
为什么临时版本需要括号?他们解决了什么歧义?
我的预感是:我认为编译器将 Bar(foo)
视为函数的声明,但我不确定为什么会出现这种情况,因为 foo
(实例)不是类型。因此,括号强制将上面的内容视为表达式,而不是前向声明。
Consider the following code:
struct Foo
{
};
struct Bar
{
explicit Bar(const Foo&)
{
}
};
int main()
{
Foo foo;
Bar bar(foo); // Okay.
Bar(foo); // Will not compile.
(Bar(foo)); // Okay. Unnamed temporary requires parenthesis.
}
Why are the parenthesis around the temporary version required? What ambiguity do they solve?
My hunch is: I think the compiler sees Bar(foo)
as a declaration for a function, but I'm not sure why that would be the case since foo
(the instance) is not a type. The parenthesis, therefore, force the above to be treated as an expression, not as a forward declaration.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
恭喜您发现最令人烦恼的解析。
斯科特·迈耶斯对此进行了如下描述:
在您的情况下,引入括号可以消除解析的歧义,迫使它成为本地解析。
Congratulations on discovering the most vexing parse.
Scott Meyers describes it as follows:
In your case, introducing parentheses disambiguates the parse, forcing it to become a local.