I have a class Foo
.
I want a function, TakeFoo
, that accepts a Foo
object and calls methods on it. This is what I started with:
void TakeFoo (const Foo&);
However, I also need to be able to call non-const methods on it. So I change it to this:
void TakeFoo (Foo&);
However, this causes warnings when I try to pass a temporary to it. So I create an overload:
void TakeFoo (Foo&&);
However, I want to reuse code, so TakeFoo(Foo&&)
basically does this:
void TakeFoo (Foo&& FooBar)
{
TakeFoo(FooBar);
}
Why is this not causing a warning as well, because I am still taking a non-const reference to a temporary?
Why is this not causing a warning as well, because I am still taking a non-const reference to a temporary?
It is not causing a warning because FooBar
is an lvalue.
Although the object it is bound to is a temporary, and although the type of FooBar
is "rvalue-reference to Foo
", the value category of a named variable is lvalue - giving something a name allows that thing to be referenced repeatably in your program (which is more or less the idea that lvalues are meant to model).
Since lvalue references can bind to lvalues in Standard C++, you are not getting any warning from the compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With