const rvalue references – useful use-cases

Rvalue references are generally used to signal a value that will no longer be used by the caller. Could be a temporary value who’s lifetime will expire when the call returns, or an lvalue which is wrapped with a std::moveto signal it will no longer be used any further. If this isn’t old news, you can review a short description here or with your favorite search engine.

When we bind an rvalue with a function call, the usual form is:


void f(A&& a)
{
   A a1;
   a1.data = a.data;
  
   // rvalue reference a is “moved” from. 
   a.data = nullptr;

   // Note: you'd likely use a swap, 
   // but this is clearer.
}

This is pretty standard stuff. Instead of making a possibly expensive copy of what member variable data contained, we take over the pointer. What this implies is that the parameter a, is modified. The very notion of rvlaue references is based on the idea that we no longer need what was passed as an argumen to the function once the call is returned, and we can extract what we need from it, and leave it in valid, yet unspecified state. But, what if the parameter was set as const in the signature?

void f(const A&& a)

What would this be??? The parameter is const, meaning we can’t extract and “steal” the underlying data in parameter a like we did above. This implies were back to the slow lane of copying if we need to copy and not just access the parameter. Binding wise, a const rvalue can already bind to this overload:

Continue readingconst rvalue references – useful use-cases