I know in c++03, an an non-const reference cannot be bound to rvalues.
T& t = getT();
is invalid, and in c++11, we can do this: T&& t = getT();
but what about the above code, should that work in c++11?
I tested the codes below with vs11:
Foo getFoo() {
return Foo();
}
void fz(Foo& f) {
}
int getInt() {
return int();
}
void iz(int& i) {
}
int main() {
{
Foo& z = getFoo(); //ok
fz(getFoo()); //ok
int& z2 = getInt(); //error: initial value of reference to non-const must be an lvalue
iz(getInt()); //same as above
}
}
Foo
is a custom class, I don't understand why the first two line compiles.The temporary referenced by z
is destructed at the end of the inner scope of main. Does the standard say anything about this?
class Foo {
public:
Foo() {
std::cout << "constructed
";
}
~Foo() {
std::cout << "destructed
";
}
};
I just saw a similar question: One VS2010 bug ? Allowing binding non-const reference to rvalue WITHOUT EVEN a warning?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…