rvalue references (T&&)

After programming in C++ for about 4/5ths of the time that it has been in existence, you would think I would stop making this mistake:(**)

extern int foo(std::string &);
 . . . 
void bar (void)
{
  string s, t;
   . . .
  int i = foo(s + t);
}

The mistake, of course, is that a non-const reference (whether a formal parameter or not) cannot be bound to a temporary object, nor any other rvalue. On a fifty-fifty cocktail of intant-rewrite-in-a-can and Homer-Simpson-doh, I hastily rearrange to the code to say:

void bar (void)
{
  string s, t, st;
   . . .
  st = s + t;
  int i = foo(st);
}

No longer. Instead, the signature of foo() can be rephrased as:

extern int foo(std::string &&);

which will allow foo to bind to the temporary created by concatenating s and t.

 

Last updated 2014-07-19T15:44:11+00:00.

Links to the standard

This addition to the language is described in section 8.3.2, although the discussion is not particularly illuminating regarding the proper use.

Benefits

This feature is valuable by itself. It has additional value regarding its interaction with other features involving move semantics and optimization.

Risks

I suppose there are a few, but not many. When I first saw the && syntax, I thought that is was an accidental typo. I mean let's face it; even the name of C++ looks like it came off a broken typewriter.