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

Temporary objects: lifetime and Extensions

Temporary objects are often created and destroyed through the normal course of a program, without much thought. That’s not entirely true, when writing efficient code, we do try to avoid temporaries when possible. Especially when they involved non trivial constructors and destructors. What I’m referring to when I saw we don’t give much thought to temporaries, is about the lifetime of temporaries (when temporaries can’t be avoided of course). When it comes to most temporaries, they are usually limited to the expression in which they are used. However, there are cases in which the lifetime is extended, some for obvious reasons and some more obscure.

Continue readingTemporary objects: lifetime and Extensions