lvalue and rvalue references

Reading Time: < 1 minute

You might’ve seen things like

int &&ref but in case you’re wondering what ref is, it’s a rvalue reference. To put in simpler terms you can use an rvalue reference to assign a reference to a constant not the variable.

See this example below

#include <cstdlib>

int main(int argc, char *argv[])
{
        int a = 10;
        int &&abc = 20;
        int &&ac = a;
        
        return EXIT_SUCCESS;
} 

In the code above, the third reference ac will give an error since it’s an rvalue reference and can’t be used with an actual variable. This comes in handy where you want to write code where it might be required to just pass on constant literals as well as variables. In that case you’ll want to have two versions of your function as shown below.

#include "references.hpp"
#include "common.h"
#include <iostream>

int updateArgument(int &lvalRef) {
#ifdef DEBUG_OUTPUT
	std::cout<<"Calling function "<< __func__ << "at line " << __LINE__ <<"\n";
#endif
	return ++lvalRef;
}

int updateArgument(int &&rvalRef) {
#ifdef DEBUG_OUTPUT
	std::cout<<"Calling function "<< __func__ << "at line " << __LINE__ <<"\n";
#endif
	return ++rvalRef;
} 

In the code above, based on what type of value i.e lvalue or rvalue is supplied, the appropriate function gets called.

Full code to above can be found in this

repository. Instructions to build are provided in the repository.

Leave a Reply