lvalue rvalue and their references in C++ 
Tags: c, cpp, beginners, programming
Published: 2019-11-11 00:31:20

<!-- wp:paragraph -->
<p>This topic might be a piece of cake for every experienced C++ veteran. But I remember back in the days when I was a novice &amp; introducing myself with <a rel="noreferrer noopener" aria-label="Modern C++ (opens in a new tab)" href="http://www.vishalchovatiya.com/21-new-features-of-modern-cpp-to-use-in-your-project/" target="_blank"><span style="color:#0e0af4" class="color">Modern C++</span></a>, I was really irritated by C++ compiler messages saying this is lvalue &amp; that is rvalue kind of jargons.  And even if you are not using C++, you may have faced compiler error in C language saying <em>"lvalue required as left operand of assignment"</em>. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>So I was getting difficulties in understanding this un-schooled topic "lvalue rvalue and their references with example in C++" until I have googled a bit for the same. This is my habit to preserve knowledge in term of an article. So here is a bit about things I had learned so far. I always start with "Why do we need that?" So let's start from there. </p>
<!-- /wp:paragraph -->

> /!\\\: Originally published @ [www.vishalchovatiya.com](http://www.vishalchovatiya.com).

<!-- wp:heading -->
<h2>Why do we need lvalue &amp; rvalue kind of jargons?</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>If you are using C++ prior to C++11 then you don't need these jargons to write code. But yes it is still useful to understand compilation errors.</li><li>The compiler sees things by expression &amp; to evaluate expression it identify operand &amp; operation. Let's understand this by example:</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">uint32_t a = 5;</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>Here compiler identifies <code>a</code> &amp; <code>5</code> as <a rel="noreferrer noopener" aria-label="operand  (opens in a new tab)" href="https://en.wikipedia.org/wiki/Operand" target="_blank"><span style="color:#313131" class="color">operand </span></a>and <code>=</code>(assignment) as operation. Furthermore, compiler divides operand in subcategory named as <code>rvalues</code>, <code>lvalues</code>, <code>xvalues</code>, <code>glvalues</code>, and <code>prvalues</code> to distinguish between them(see heading <a rel="noreferrer noopener" aria-label="image  (opens in a new tab)" href="http://secureservercdn.net/160.153.137.218/bkh.972.myftpupload.com/wp-content/uploads/20-new-features-of-Modern-C-to-use-in-your-project.png" target="_blank"><span style="color:#040cf5" class="color">image </span></a>for hierarchy). This different value type tells the compiler about the source, destination, the scope of information, etc.</li><li>In the above expression <code>a</code> is lvalue as it indicates destination memory where rvalue i.e. <code>5</code> will be stored.</li><li>When you compile &amp; see above statement in assembly, it would probably look like :</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock -->
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">...
movl    $5, -4(%ebp)
...</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>Here, <code>(%ebp)</code> is current frame pointer which pulls down by 4 bytes which indicate <a rel="noreferrer noopener" aria-label="space allocated by the compiler for a variable in a stack (opens in a new tab)" href="http://www.vishalchovatiya.com/how-c-program-convert-into-assembly/" target="_blank"><span style="color:#2708ec" class="color">space allocated by the compiler for a variable in a stack</span></a>. And <code>movl</code> instruction store <code>5</code> to that memory location directly.</li><li>This is straight forward as long as we are using primitive data types like <code>int</code>, <code>double</code>, <code>char</code>, etc. So compiler will store raw value directly in instruction code itself like in our case its <code>$5</code>. After the execution of that instruction, <code>$5</code> is not used, so it has an expression scope, in other words, it is temporary.</li><li>But when we use class &amp; struct which are the user-defined type, things get bit complex &amp; compiler introduce temporary object instead of directly storing the value in instruction code itself.</li></ul>
<!-- /wp:list -->


<!-- wp:heading -->
<h2>lvalue rvalue and their references with example</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3><strong>What are lvalue &amp; rvalue?</strong></h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>lvalue &amp; rvalue is compiler identifiers to evaluate the expression.</li><li>Any compiler identifier which represents memory location is an lvalue. </li><li>Any compiler identifier which represents data value on the right-hand side of an <a rel="noreferrer noopener" aria-label="assignment operator (opens in a new tab)" href="http://www.vishalchovatiya.com/2-wrong-way-to-learn-copy-assignment-operator-in-cpp-with-example/" target="_blank"><span style="color:#3113ee" class="color">assignment operator</span></a>(=) is rvalue.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3><strong>Examples of lvalue</strong></h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>There are two types of lvalue modifiable &amp; non-modifiable(which are <code>const</code>).</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>1. <strong>modifiable lvalue</strong></p>
<!-- /wp:paragraph -->

<!-- wp:table {"align":"center","className":"is-style-stripes"} -->
<table class="wp-block-table aligncenter is-style-stripes"><tbody><tr><td><strong>Expression</strong></td><td><strong>Explanation</strong></td></tr><tr><td><code>a = 1; </code></td><td><strong>a</strong> is lvalue as it represents memory</td></tr><tr><td><code>int b = a; </code></td><td><strong>b</strong> &amp; <strong>a </strong>is an lvalue, when <strong>a</strong> is assigned to <strong>b</strong>. It becomes an implicit rvalue because of a copy of <strong>a</strong> is stored in <strong>b</strong>, not <strong>a</strong> itself</td></tr><tr><td><code>struct S* ptr = &amp;obj;</code> </td><td><strong>ptr </strong>is lvalue </td></tr><tr><td><code>arr[20] = 5; </code></td><td>location index 20 in <strong>arr </strong>is lvalue </td></tr><tr><td><code>int *pi = &amp;i; </code><br><code>*pi = 10;</code> </td><td><strong>i </strong>is lvalue as it is addressable. <strong>*pi</strong> is lvalue as it points to <strong>i</strong> </td></tr><tr><td><code>class MyClass {}; MyClass X; </code></td><td><strong>X</strong> is lvalue as it represents the memory of user-defined type</td></tr></tbody></table>
<!-- /wp:table -->

<!-- wp:paragraph -->
<p>2. <strong>non-modifiable lvalue</strong></p>
<!-- /wp:paragraph -->

<!-- wp:table {"className":"is-style-stripes"} -->
<table class="wp-block-table is-style-stripes"><tbody><tr><td><strong>Expression</strong> </td><td><strong>Explanation</strong> </td></tr><tr><td> <code>const int a=1;</code></td><td><strong>a</strong> is non-modifiable lvalue </td></tr><tr><td> <code>const int *p=&amp;a;</code></td><td><strong>p</strong> is non-modifiable lvalue </td></tr></tbody></table>
<!-- /wp:table -->

<!-- wp:heading {"level":3} -->
<h3><strong>Examples of rvalue</strong></h3>
<!-- /wp:heading -->

<!-- wp:table {"className":"is-style-stripes"} -->
<table class="wp-block-table is-style-stripes"><tbody><tr><td><strong>Expression</strong>  </td><td><strong>Explanation</strong>  </td></tr><tr><td> <code>int a = 1;</code></td><td><strong>1</strong> is rvalue </td></tr><tr><td> <code>int b = a;</code></td><td><strong>a </strong>is implicit rvalue this case we have already discussed in 2nd point of "Examples of lvalue" </td></tr><tr><td> <code>q = p + 5;</code></td><td>valid - <strong>p + 5 </strong>is an rvalue </td></tr><tr><td><code>int result = getInteger(); </code></td><td>the value returned by<strong> getInteger()</strong> is rvalue</td></tr><tr><td> <code>class cat {}; c = cat();</code></td><td><strong>cat() </strong>is an rvalue </td></tr></tbody></table>
<!-- /wp:table -->

<!-- wp:list -->
<ul><li>rvalue could be a function on the right-hand side of = assignment operator which eventually evaluate to object(primitive or user-defined).</li><li>rvalues are typically evaluated for their values, have expression scope (they die at the end of the expression they are in) most of the time, and cannot be assigned to. For example:</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">5 = a; // invalid
getInt() = 2; // invalid</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:heading {"level":3} -->
<h3>lvalue rvalue references with example </h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p><strong>lvalue reference </strong></p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>An lvalue reference is a reference that binds to an lvalue. </li><li>lvalue references are marked with one ampersand <code>&amp;</code>.</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">int x = 5;
int &amp;lref = x; // lvalue reference initialized with lvalue x</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>Prior to C++11, only one type of reference existed in C++, and so it was just called a “reference”. However, in C++11, it’s sometimes called an lvalue reference. </li><li>lvalue references can only be initialized with modifiable lvalues.</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const int a = 5;
int &amp;ref = a; // Invalid &amp; error will be thrown by compiler</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:paragraph -->
<p><strong>Exception</strong></p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>We cannot bind lvalue reference to an rvalue</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">int &amp;a = 5; // error: lvalue cannot be bound to rvalue 5</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:paragraph -->
<p>However, we can bind an rvalue to a const lvalue reference (<a rel="noreferrer noopener" aria-label="const (opens in a new tab)" href="http://www.vishalchovatiya.com/when-to-use-const-vs-constexpr-in-cpp/" target="_blank"><span style="color:#2e08e9" class="color">const</span></a> reference):</p>
<!-- /wp:paragraph -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const int &amp;a = 5;  // Valid</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>In this case, the compiler converts <code>5</code> into lvalue first &amp; then it assigns memory location to a const reference.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p><strong>rvalue reference</strong></p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>This is by far the most useful &amp; bit complex thing you will learn.</li><li>An rvalue reference is a reference that binds to an rvalue. rvalue references are marked with two ampersand <code>&amp;&amp;</code>.</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">int &amp;&amp;rref = 5; // rvalue reference initialized with rvalue 5</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>rvalues references cannot be initialized with lvalues i.e. </li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">int a = 5;
int &amp;&amp;ref = a; // Invalid &amp; error will be thrown by compiler</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>rvalue references are more often used as function parameters. This is most useful for function overloads when you want to have different behaviour for lvalue and rvalue arguments.</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">void fun(const int &amp;lref) // lvalue arguments will select this function
{
    std::cout &lt;&lt; "lvalue reference to const\n";
}

void fun(int &amp;&amp;rref) // rvalue arguments will select this function
{
    std::cout &lt;&lt; "rvalue reference\n";
}

int main()
{
    int x = 5;
    fun(x); // lvalue argument calls lvalue version of function
    fun(5); // rvalue argument calls rvalue version of function

    return 0;
}</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:heading -->
<h2>Why we need rvalue references?</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>If you observe the <a rel="noreferrer noopener" aria-label="copy constructor (opens in a new tab)" href="http://www.vishalchovatiya.com/all-about-copy-constructor-in-cpp-with-example/?preview=true&amp;_thumbnail_id=1695" target="_blank"><span style="color:#1d19f2" class="color">copy constructor</span></a> &amp; <a rel="noreferrer noopener" aria-label="copy assignment operator (opens in a new tab)" href="http://www.vishalchovatiya.com/2-wrong-way-to-learn-copy-assignment-operator-in-cpp-with-example/" target="_blank"><span style="color:#2816f2" class="color">copy assignment operator</span></a> prototype, it always takes <code>const</code> reference object as an argument. Because their primary work is to copy the object. And while copying we don't want to modify the object we have provided on the right-hand side.</li><li>But there are some scenarios where we don't care about the right-hand side object we have provided to copy from. For example:</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class IntArray{
    int *m_arr;
    int m_len;
public:
    IntArray(int len) : m_len(len), m_arr(new int[len]){}
    ~IntArray(){delete [] m_arr;}

    // Copy Constructor
    IntArray(const IntArray&amp; rhs){
      m_arr = new int[rhs.m_len];
      m_len = rhs.m_len;

      for(int i=0;i&lt;m_len;i++)
        m_arr[i] = rhs.m_arr[i];
    }
};

IntArray func()
{
    IntArray obj(5);    
    // process obj    
    return obj;
}

int main()
{
  IntArray arr = func();   
  return 0;
}

// Note: use "-fno-elide-constructors" option while compiling otherwise it will create copy elision </pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>By observing this code we conclude that <code>obj</code> is not useful after the return of <code>func()</code> function. But when you return an <a rel="noreferrer noopener" aria-label="object  (opens in a new tab)" href="http://www.vishalchovatiya.com/inside-the-cpp-object-model/" target="_blank"><span style="color:#0d11f0" class="color">object </span></a>by the value it will invoke copy constructor &amp; which will copy all the content from <code>obj</code> to <code>arr</code>(declared in <code>main()</code>) by allocating new resource for <code>arr</code>. And when <code>obj</code> goes out of scope it will deallocate its resources.</li><li>Rather than allocating new resources &amp; copying data into it why don't we simply use those existing <code>obj</code>'s resources? Let's do that:</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>move constructor</h3>
<!-- /wp:heading -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">IntArray(IntArray&amp;&amp; rhs){
    m_arr = rhs.m_arr;
    m_len = rhs.m_len;

    rhs.m_arr = nullptr; // To prevent code crashing 
}</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>I have just modified copy constructor code as above which accept rvalue reference as an argument rather than lvalue so that our overloaded copy constructor will only be called when there is an rvalue is used on the right-hand side. </li><li>Which simply means this constructor will only be called when right-hand side object is temporary or programmer is no longer care about that object. </li><li>The implementation simply took ownership of resources from <code>obj</code> to <code>arr</code> and set right-hand side object's pointer to <code>NULL</code> so that its destructor won't deallocate resource which it is no longer owning.</li><li>In fact, this is move constructor, not a copy constructor. Whose primary task is to take/move ownership of resources.</li><li>Consider following move constructor prototype for more solid understanding:</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Catching rvalue reference</h2>
<!-- /wp:heading -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">IntArray(IntArray&amp;&amp; rhs)
{
    ...
}</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>The message of this code is this: "The object that <code>rhs</code> binds to is YOURS. Do whatever you like with it, no one will care anyway." It's a bit like giving a copy to <code>IntArray</code> but without making a copy.</li></ul>
<!-- /wp:list -->

<!-- wp:yoast/faq-block {"questions":[{"id":"faq-question-1572779853349","question":["Why do we need move constructor?"],"answer":["This can be interesting for two purposes:  ",{"type":"br","props":{"children":[]}},"    - improving performance (as we are not allocating new resources \u0026 transferring content).",{"type":"br","props":{"children":[]}},"    - taking over ownership (since the object the reference binds to has been abandoned by the caller). "],"jsonQuestion":"Why do we need move constructor?","jsonAnswer":"This can be interesting for two purposes:  \u003cbr/\u003e    - improving performance (as we are not allocating new resources \u0026amp; transferring content).\u003cbr/\u003e    - taking over ownership (since the object the reference binds to has been abandoned by the caller). "}]} -->
<div class="schema-faq wp-block-yoast-faq-block"><div class="schema-faq-section"><strong class="schema-faq-question">Why do we need move constructor?</strong> <p class="schema-faq-answer">This can be interesting for two purposes:  <br/>    - improving performance (as we are not allocating new resources &amp; transferring content).<br/>    - taking over ownership (since the object the reference binds to has been abandoned by the caller). </p> </div> </div>
<!-- /wp:yoast/faq-block -->

<!-- wp:list -->
<ul><li>I know you might be thinking that why just we don't modify copy constructor by removing <code>const</code> keyword from it. Let's do that as well</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">IntArray(IntArray&amp; rhs){
}</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>Compilation error</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock -->
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">exit status 1
error: no matching constructor for initialization of 'IntArray'
  IntArray arr = func();
           ^     ~~~~~~
note: candidate constructor not viable: expects an lvalue for 1st argument
    IntArray(IntArray&amp; rhs){
    ^
1 error generated.</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>If you see the <code>note</code> above, our overloaded copy constructor asking for lvalue. What we are doing is providing rvalue. As when we return an object by value, temporary(which falls under rvalue category) object will be created and supplied to our copy constructor. And as we have already seen above lvalue reference cannot bind to rvalue object.</li><li>Don't think about changing your copy constructor's argument as <code>const</code> lvalue reference, I know we have seen that its exception &amp; we can bind <code>const</code> lvalue reference to rvalue/temporary object. But in that case, you can not move/transfer resource as it is <code>const</code>.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>So, this is it for "lvalue rvalue and their references with example", in the <a rel="noreferrer noopener" aria-label="next (opens in a new tab)" href="http://www.vishalchovatiya.com/understanding-unique-ptr-with-example-in-cpp11/" target="_blank"><span style="color:#1317f3" class="color">next</span></a> article we will design <a rel="noreferrer noopener" aria-label="smart pointer (opens in a new tab)" href="http://www.vishalchovatiya.com/move-constructor-assignment-operator-with-shared-ptr/" target="_blank"><span style="color:#3c0cfd" class="color">smart pointer</span></a> using rvalue reference &amp; other concepts gained here.</p>
<!-- /wp:paragraph -->

## You may like

- [21 new features of Modern C++ to use in your project](https://dev.to/visheshpatel/21-new-features-of-modern-c-to-use-in-your-project-3f87)
- [All about lambda functions in C++(from C++11 to C++17)](https://dev.to/visheshpatel/all-about-lambda-function-in-c-from-c-11-to-c-17-3p5h)
- [C++ type casting with example for C developers](https://dev.to/visheshpatel/c-type-casting-with-example-for-c-developers-29b8)