+1 vote
in C Plus Plus by

Rvalue References in C++

1 Answer

0 votes
by
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;

 a=b;

 b=temp;

}

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

 empty.setsize(filled.size());

 empty.setdata(filled.data());

//filled becomes empty

 filled.setsize(sz);

 filled.setdata(p);

}

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.

Related questions

+1 vote
asked Jan 2, 2020 in C Plus Plus by GeorgeBell
+1 vote
asked Jan 2, 2020 in C Plus Plus by GeorgeBell
+1 vote
asked Jan 2, 2020 in C Plus Plus by GeorgeBell
+1 vote
asked Jan 2, 2020 in C Plus Plus by GeorgeBell
+1 vote
asked Jan 2, 2020 in C Plus Plus by GeorgeBell
+1 vote
asked Jan 2, 2020 in C Plus Plus by GeorgeBell
+1 vote
asked Jan 2, 2020 in C Plus Plus by GeorgeBell
+1 vote
asked Jan 2, 2020 in C Plus Plus by GeorgeBell
0 votes
asked Jan 2, 2020 by GeorgeBell
+1 vote
asked Mar 17, 2020 in C Plus Plus by SakshiSharma
...