c++ lvalue reference, rvalue reference, and const
Created on Oct 29, 2024
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.
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.
int && x = 3; // OK. Rvalue reference x is initialized with rvalue 3.
Rvalue reference is also called non-const rvalue reference.
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.
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 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.
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.
c++ std::exception:
std::cout.write(err.data(), err.size());
std::cout << std::endl;
caught:
================================================== # The c++ programming language. # # # # Home: cppfx.xyz # # Join c++ Discord: yZcauUAUyC # # Deck # ==================================================