DigestCPP

Lets Understand With Example

  • Home
  • Design Principal
  • Design Patterns
  • C++ 11 Features
  • C++11 Multithreading
  • Contact Us

lvalue reference and rvalue reference c++11

lvalue reference

It is our old reference and got another new name. It is represented by (&) and it is used for reference to lvalue so it is called lvalue reference. In other word it means “alternate name”. It must be initialised otherwise it will give compilation error.

Example:

int x{8};
int& refX{x};
//int&y; //It will below error
//error: ‘y’ declared as reference but not initialized
std::cout<<"lvalue reference:"<<refX<<std::endl;
Output:
lvalue reference:8

rvalue reference

It is represented by (&&) and it is used to reference to rvalue so it is called rvalue reference. In other word it is meant to refer to temporary object. It can bind to rvalue only (cannot bind to lvalue).

Example:

int&& rref{5};
std::cout<<"rvalue reference:"<<rref<<std::endl;
Output:
rvalue reference:5

source code with example:

/*
Program: lvalue reference & rvalue reference 
Author: Alpha Master
Date: 7 March 2021
*/

//Header File
#include<iostream>

std::string fun()
{
    return("www.digestcpp.com");
}

int main()
{
    std::cout<<"lvalue reference & rvalue reference"<<std::endl;
    std::string str1{"digestcpp.com"};
    //lvalue examples
    std::string& lv1{str1};
    std::cout<<"lvalue ref with lvalue:"<<lv1<<std::endl;
    //Below example lvalue reference cannot bind to rvalue
    //std::string& lv2{fun()}; //lvalue reference cannot bind to rvalue
    //error: invalid initialization of non-const reference of type ‘std::__cxx11::string&’ from an rvalue of type
    //std::string& lv3{"digestcpp"};  //lvalue reference cannot bind to rvalue
    //error: invalid initialization of non-const reference of type ‘std::__cxx11::string&’ from an rvalue of type

    //Below example rvalue reference cannot bind to lvalue
    //std::string&& rv1{str1}; //rvalue reference cannot bind to lvalue
    //error: cannot bind lvalue to ‘std::__cxx11::string&& {aka std::__cxx11::basic_string<char>&&}’
    //rvalue examples
    std::string&& rv2{fun()};
    std::cout<<"rvalue ref with rvalue:"<<rv2<<std::endl;
    std::string&& rv3{"digestcpp"};
    std::cout<<"rvalue ref with rvalue:"<<rv3<<std::endl;

    return 0;
}

Output:

lvalue reference & rvalue reference
lvalue ref with lvalue:digestcpp.com
rvalue ref with rvalue:www.digestcpp.com
rvalue ref with rvalue:digestcpp

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer