Categories

Jan 2 in C++

Q:

Rvalue References in C++

1 Answer

Jan 2
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.
Click here to read more about C++
Click here to read more about Insurance

Related questions

Madanswer
Jan 2 in C++
Mar 17 in C++
Jul 16, 2019 in C++
...