Jan 2, 2020 in C Plus Plus

Rvalue References in C++

1 Answer

0 votes
Jan 2, 2020
Reference types in C++03 can only bind to lvalues. C++11 introduces a new category of reference types called rvalue references. Rvalue references can bind to rvalues, e.g. temporary objects and literals.

The primary reason for adding rvalue references is move semantics. Unlike traditional copying, moving means that a target object pilfers the resources of the source object, leaving the source in an "empty" state. In certain cases where making a copy of an object is both expensive and unnecessary, a move operation can be used instead. To appreciate the performance gains of move semantics, consider string swapping. A naive implementation would look like this:

void naiveswap(string &a, string & b)


 string temp = a;




This is expensive. Copying a string entails the allocation of raw memory and copying the characters from the source to the target. In contrast, moving strings merely swaps two data members, without allocating memory, copying char arrays and deleting memory:

void moveswapstr(string& empty, string & filled)


//pseudo code, but you get the idea

 size_t sz=empty.size();

 const char *p= empty.data();

//move filled's resources to empty



//filled becomes empty




If you're implementing a class that supports moving, you can declare a move constructor and a move assignment operator like this:

class Movable


Movable (Movable&&); //move constructor

Movable&& operator=(Movable&&); //move assignment operator


The C++11 Standard Library uses move semantics extensively. Many algorithms and containers are now move-optimized.
Click here to read more about Loan/Mortgage
Click here to read more about Insurance

Related questions

+1 vote
+1 vote
+1 vote
+1 vote
+1 vote
Jan 2, 2020 in C Plus Plus
+1 vote