11

In my adventures studying the boost libraries, I've come across function signatures that have parameters which are a reference to a reference to an object.

Example:

void function(int && i);

What is the purpose/benefit of doing it this way rather than simply taking a reference to an object? I assume there is one if it's in boost.

Nick Strupat
  • 4,928
  • 4
  • 44
  • 56

3 Answers3

18

This is not a reference to a reference; there is no such thing.

What you're seeing is a C++0x rvalue reference, denoted by double ampersands, &&. It means that the argument i to the function is a temporary, so the function is allowed to clobber its data without causing problems in the calling code.

Example:

void function(int &i);  // A
void function(int &&i); // B
int foo();

int main() {
    int x = foo();
    function(x);     // calls A
    function(foo()); // calls B, because the return value is a temporary
}

This rarely useful with plain ints, but very useful when defining move constructors, for example. A move constructor is like a copy constructor, except that it can safely 'steal' the internal data from the original object, because it's a temporary that will cease to exist after the move constructor returns.

Thomas
  • 174,939
  • 50
  • 355
  • 478
  • Ah, ok. Thank you for the clarification. How is this code in boost (1.42) right now? It's my understanding that boost is currently written for the C++03 standard. – Nick Strupat Apr 18 '10 at 20:25
  • 2
    @Silver: It'll take advantage of features of certain compilers. Some compilers support C++0x (a bit), and if Boost wants to detect and use that, it will. – GManNickG Apr 18 '10 at 20:27
  • 1
    @SilverSun: Boost uses conditional compilation (#if, etc.) to customize what's available for each compiler. –  Apr 18 '10 at 20:31
3

That is not a reference to a reference. It is an rvalue reference, which is a new feature supported by the upcoming C++0x standard.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
2

What you are looking at is an rvalue-reference. It is a new core language feature of C++0x. See here or less formaly here.

The original proposal can be found here

pmr
  • 58,701
  • 10
  • 113
  • 156