Search code examples
c++c++11lvaluervalue

Confused with r-values and l-values


I read recently on a whitepaper on C++11, that if I write,

void foo(X&)

This will be called for l-values but not for r-values

and if I write,

void foo(const X&)

This will be called for both r-value and l-value.

Could someone give me an example what this means here ?


Solution

  • This function accepts a lvalue reference

    void foo(X&)
    

    and trying to call it with an rvalue would yield an error.

    This function expects a const lvalue reference

    void foo(const X&)
    

    but there's a catch:

    An rvalue may be used to initialize a const lvalue reference, in which case the lifetime of the object identified by the rvalue is extended until the scope of the reference ends.

    from cppreference

    So it is true that this last function accepts both lvalue and rvalue parameters

    struct X {};
    
    void foo(X&) {
    }
    
    void fooC(const X&) {
    }
    
    int main() { 
       X obj;
       // foo(std::move(obj)); // Error - non-const
       foo(obj); // Valid
       fooC(obj); // Valid
       fooC(std::move(obj)); // Valid
    }
    

    For more information take a look at here: reference initialization or check [dcl.init.ref]/p5