Characteristic
- stored on location that are not accessible to programmer
- processor registers
- Literals like 2 or ‘c’
- Temporary objects
- Destroyed in the same statement in which they are created
Rvalue reference
- Since C++11
- This is a syntactic device which indicates that a function argument must be a moveable rvalue
- ’&&’ after type
void func(int&& x);
func(2); // 2 is an rvalue, OK
int y{2};
func(y); // Error: y is an lvalue- A function argument can be an “rvalue reference”
- The passed object will be moved into the argument if
- The object is an rvalue
- and its type is moveable
- Otherwise, the call does not compile
- This allow overloading the function to behaves differently depending on whether the passed object is an rvalue or lvalue
Tip
can pass a movable rvalue, but not an lvalue
the function now owns the passed object’s data
Rvalue overloading
Info
function can be overloaded so that it behaves differently depending on whether its argument is moved
void func(const myclass& obj); // called when an lvalue is passed
void func(myclass&& obj); // called when an rvalue is passed
most useful functions to be overloaded this way are copy constructor and assignment operator
Test(const Test& arg); // Copy constructor
Test(Test&& arg) noexcept; // Move constructor
Test& operator=(const Test& arg); // Copy assignment operator
Test& operator=(Test&& arg) noexcept; // Moe assignment operatora