Passing by reference after receiving via r-value link

I have a Foo class.

I need a TakeFoo function that takes a Foo object and calls methods on it. This is where I started:

 void TakeFoo (const Foo&); 

However, I also need to be able to call non-constant methods on it. Therefore, I change this to the following:

 void TakeFoo (Foo&); 

However, this triggers warnings when I try to give it a temporary. Therefore, I create an overload:

 void TakeFoo (Foo&&); 

However, I want to reuse the code, so TakeFoo(Foo&&) basically does this:

 void TakeFoo (Foo&& FooBar) { TakeFoo(FooBar); } 

Why doesn't this raise a warning because I'm still not referring to the temporary?

+4
source share
1 answer

Why doesn't this raise a warning because I'm still not referring to the temporary?

This does not raise a warning because FooBar is an lvalue.

Although the object to which it is attached is temporary, and although the FooBar type is "rvalue-reference to Foo " the value category of the named variable is lvalue - giving something a name allows this thing to be referenced to your program (this is more or less the idea that lvalues ​​are for modeling).

Since lvalue links can link to lvalues ​​in standard C ++, you do not receive warnings from the compiler.

+7
source

Source: https://habr.com/ru/post/1487111/


All Articles