PrevUpHomeNext

02. c++ lvalue reference, rvalue reference, const


c++ lvalue reference, rvalue reference, and const

Created on Oct 29, 2024

c++ lvalue reference

Lvalue ref

int a;
int & x = a;	// OK. Lvalue reference x is initialized with lvalue a.

Lvalue reference is also called non-const lvalue reference.

It can be also described as non-const lvalue reference x is bound to lvalue a.

Mistake Cases

int & a; // Error, lvalue reference a must be initialized when it is declared.

int & b = 3; // Error, lvalue reference b must be initialized with an lvalue, 3 is rvalue.

c++ rvalue reference

Rvalue ref

int && x = 3;	// OK. Rvalue reference x is initialized with rvalue 3.

Rvalue reference is also called non-const rvalue reference.

Mistake Cases

int && a; // Error, rvalue reference must be initialized when it is declared.
int t = 24;
int && a = t;	// Error. rvalue reference a must be initialized with rvalue, t is lvalue.

Rvalue reference is also called non-const rvalue reference.

const

A const qualified variable must be initialized.

const int x = 3;	// OK
const int y;	// Error, not initialized

const lvalue reference and const rvalue reference must initialize their bindings.

const lvalue reference

const lvalue reference can be bound to either lvalue or rvalue, either const or non-const value.

const qualifier makes the const-lvalue-reference immutable.

A const-lvalue-reference must initialize its binding.

int a;
const int & x = a;
int const & y = 5;	// Note that const int & and int const & are the same type.

const rvalue reference

A const rvalue reference can be bound to an rvalue, it can not be bound to an lvalue.

const qualifier makes the const-rvalue-reference immutable.

A const-rvalue-reference must initialize its binding.

const int && x = 3;
int a;
const int && x = a;	// ERROR, const rvalue reference x can not be bound to lvalue a.

cpp/c++

c++ std::exception:

std::cout.write(err.data(), err.size());

std::cout << std::endl;

caught:

  ==================================================
  #        The c++ programming language.           #
  #                                                #
  #        Home: cppfx.xyz                         #
  #        E                                       #
  #        Deck                                    #
  ==================================================

PrevUpHomeNext