4

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?

TripShock
  • 4,081
  • 5
  • 30
  • 39

1 Answers1

7

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.

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
  • This doesn't really address the root issue though, which is `"Why is the OP (potentially) trying to mutate a temporary"`. – Mark B Jun 19 '13 at 18:12
  • @MarkB: Indeed it does not, but I believe it answers the OP's question, and I assume that's enough for the OP - they are giving no context, so I assume they are only curious about the compiler's behavior. – Andy Prowl Jun 19 '13 at 18:26
  • Thanks. Yes, you answered this question, my bigger question is here: http://stackoverflow.com/questions/17199695/how-to-override-no-non-const-reference-to-temporary-object-correctly – TripShock Jun 19 '13 at 19:29