Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing by reference after receiving by r-value reference

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?

like image 208
TripShock Avatar asked Mar 24 '23 12:03

TripShock


1 Answers

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.

like image 149
Andy Prowl Avatar answered Apr 25 '23 04:04

Andy Prowl