Doubt about parameters && in functions


Could someone explain to me what it means, a parameter defined with & & amp;


strc::strc(strc && o) {
    data = std::move(; = nullptr;
    msg("move ctor");

Thanks. JC

asked by Jcpardo 11.05.2018 в 22:19

1 answer


&& is a modifier , present from C ++ 11, known as rvalue reference (right-hand reference).

It's similar to the classic reference (&) of C ++, with certain differences:

  • The original data it refers to, is mutable (there is no const && , it's illegal).
  • The original data it refers to, is temporary .

The latter requires a more detailed explanation. Let's see a simple example function:

std::string dup( const std::string &arg ) { return std::string( arg ); }

A simple function, which returns a copy of the argument; to use it, we could do

std::string duplicated = dup( std::string( ) );

Let's see what happens in that line:

  • An instance of std::string is created, calling its default constructor.
  • dup( ) is called, passing as a constant reference argument to the newly created instance.
  • dup( ) is executed and returned.
  • The instance created in point 1 is destroyed
  • That is a temporary instance; basically, a data that is not linked to an identifier .

    A detail of this, source of many errors, is the following:

    std::string dup( string &&orig ) {
      std::string ret( orig );
      return ret;

    Note that orig is temporary outside the function , but within it, it is not . Inside the function if it has a name .

    This is intentional, and allows certain language usage facilities: allows to continue using old code .

    Since C ++ 11, the compiler takes this switch into account to choose the specific function to call:

    std::string dup( const std::string &s ); // no temporal.
    std::string dup( std::string &&s ); // temporal.

    So, do we have to define 2 versions of each function? Well not , because the compiler, in the absence of the version // temporal , uses the version // no temporal . And the only way to achieve this is that, within the function, an argument && behaves just like one & .

    It may seem confusing at first, but its use provides a very important optimization : from C ++ 11, objects can be copied (as before) ... and move ; we detect if it is temporary, and, instead of copying, we move the data.

    This has repercussions on fewer resource use / release operations, including memory; it has been historically the great heel of achilles of C ++, and with this new modifier, much progress has been made in this. Personally, I think that only this is enough to make the leap from previous versions.

    answered by 11.05.2018 / 23:58