Search code examples
c++parametersc++11rvalue-referencelvalue

Any way to pass an rvalue/temp object to function that expects a non-cost reference?


I understand that c++ only allows rvalues or temp objects to bind to const-references. (Or something close to that...)

For example, assuming I have the functions doStuff(SomeValue & input)
and SomeValue getNiceValue() defined:

/* These do not work */
app->doStuff(SomeValue("value1"));
app->doStuff(getNiceValue());

/* These all work, but seem awkward enough that they must be wrong. :) */

app->doStuff(*(new SomeValue("value2")));

SomeValue tmp = SomeValue("value3");
app->doStuff(tmp);

SomeValue tmp2 = getNiceValue();
app->doStuff(tmp2);

So, three questions:

  1. Since I am not free to change the signatures of doStuff() or getNiceValue(), does this mean I must always use some sort of "name" (even if superfluous) for anything I want to pass to doStuff?

  2. Hypothetically, if I could change the function signatures, is there a common pattern for this sort of thing?

  3. Does the new C++11 standard change the things at all? Is there a better way with C++11?

Thank you


Solution

  • An obvious question in this case is why your doStuff declares its parameter as a non-const reference. If it really attempts to modify the referred object, then changing function signature to a const reference is not an option (at least not by itself).

    Anyway, "rvalue-ness" is a property of an expression that generated the temporary, not a property of temporary object itself. The temporary object itself can easily be an lvalue, yet you see it as an rvalue, since the expression that produced it was an rvalue expression.

    You can work around it by introducing a "rvalue-to-lvalue converter" method into your class. Like, for example

    class SomeValue {
    public:
      SomeValue &get_lvalue() { return *this; }
      ...
    };
    

    and now you can bind non-const references to temporaries as

    app->doStuff(SomeValue("value1").get_lvalue());
    app->doStuff(getNiceValue().get_lvalue());
    

    Admittedly, it doesn't look very elegant, but it might be seen as a good thing, since it prevents you from doing something like that inadvertently. Of course, it is your responsibility to remember that the lifetime of the temporary extends to the end of the full expression and no further.

    Alternatively, a class can overload the unary & operator (with natural semantics)

    class SomeValue {
    public:
      SomeValue *operator &() { return this; }
      ...
    };
    

    which then can be used for the same purpose

    app->doStuff(*&SomeValue("value1"));
    app->doStuff(*&getNiceValue());
    

    although overriding the & operator for the sole purpose of this workaround is not a good idea. It will also allow one to create pointers to temporaries.