C++ – What are R-value references used for

cc++11

I'm trying to dig deep into C++ and really learn the nuances of the language but one thing I've found to be really confusing is the R-Value reference. The whole double ampersand thing to be clear (in case I'm getting the terminology wrong). It's not a big deal as it doesn't seem to come up often but it seems like it could occasionally be useful to know.

Best Answer

A common use case is the “move constructor,” invoked when an object is being copied from a temporary that’s about to expire (a rvalue). An example is foo = bar + baz; where bar + baz is a temporary on the right-hand side of an assignment statement.

Before rvalue references, objects that made deep copies of their contents had to construct their data in one place, then copy it all to another, then destroy the first copy. This was slow and wasteful.

When the source is a rvalue reference, the move constructor or assignment operator will typically make a shallow copy of the source’s data, then remove the source’s references so that it will be an empty shell when it’s deleted a moment later and the data will now have a new owner. This is safe, because a rvalue reference won’t be used for anything else before it’s destroyed, much faster, and saves memory.