C++ const 引用绑定到右值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1310643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:31:32  来源:igfitidea点击:

const reference binding to an rvalue

c++c++11

提问by fnieto - Fernando Nieto

Working on thisquestion, I found an inconsistent behavior.

在解决这个问题时,我发现了不一致的行为。

Why reference binding behave different in a constructor from a common function?

为什么引用绑定在构造函数中的行为与普通函数不同?

struct A {
};

struct B : public A {
  B(){}
private:
  B(const B&);
};

void f( const B& b ) {}

int main() {
  A a( B() ); // works
  A const & a2 = B(); // C++0x: works, C++03: fails
  f( B() );  // C++0x: works, C++03: fails
}

I have tested it for C++03 with g++-4.1 and Comeau 4.2.45.2 in strict C++03 mode and with C++0x extensions disabled. I got same results.

我已经在严格的 C++03 模式下使用 g++-4.1 和 Comeau 4.2.45.2 对 C++03 进行了测试,并禁用了 C++0x 扩展。我得到了同样的结果。

For C++0x was tested with g++-4.4 and Comeau 4.3.9 in relaxed mode and with C++0x extensions enabled. I got same results.

对于 C++0x,在宽松模式下使用 g++-4.4 和 Comeau 4.3.9 进行了测试,并启用了 C++0x 扩展。我得到了同样的结果。

回答by AProgrammer

A a(B());

is the declaration of a function named a returning an A and taking a pointer to a function without argument returning a B. See here. Add parenthesis and you'll get the error you expect:

是一个名为 a 的函数的声明,它返回一个 A 并使用一个指向函数的指针,而没有参数返回一个 B。请参见 此处。添加括号,你会得到你期望的错误:

A a((B()));