VC编译器与GCC编译在引用上的不同?


   
  class A {};
  

void f(A &a) {}

int main() {
A& a = A(); //GNU GCC 编译错误
f(A()); //GNU GCC 编译错误
return 0;
}

GCC 编译报错 error: invalid initialization of non-const reference of type 'A&' from a temporary of type 'A'|
c++程序设计语言 书中也提到过这个问题。
const引用才允许临时对象赋值给引用的。
void f(const A &a) {}
const A& a = A(); 这样才是被允许的做法
VC内部做了什么优化吗,还是我VC设置的问题。怎么让VC也报出这个错?

visualstudio C++

万年受QAQ 13 years, 2 months ago

C++11好像允许这么用了。VC有一部分C++11的特性。之前的C++标准在这方面规定的非常不清楚。
准确来说临时变量应该产生一个右值。

vzvae answered 13 years, 2 months ago

Your Answer