How are the && and & parameters different in C++

Implemented from C++11


How are the && and & parameters different in C++

We already know that the & parameter refers to the reference in C/C++ , but as of C++11 we can find the && and it refers to the value on the other side of the declaration.

More objectively we can say, for example, that:

&& = &

Equals:

int x = 3;

Of course, values and types are examples.

But in summary, one is the lvalue and the other is the rvalue .

In C++03 (and before), temps (called “rvalues”, as they often lie on the right side of an assignment) were designed to never be modifiable - just as in C - and were considered indistinguishable from const types T&; , however, in some cases the temps may have been modified, a behavior that was even considered a useful loophole.

C++11 adds a new non-const reference type called the rvalue reference, identified by T&&. Refers to temporaries that can be modified after they are initialized, for the purpose of allowing “semantic move”.

Usage examples

Using && as a parameter, let’s look at the output:

#include <iostream>

void the_int( const int * && i ){
  std::cout << &i << '\n'; // address
  std::cout << i << '\n'; // copy
  std::cout << *i << '\n'; // value
}

int main(){
  int &&x = 3;
  the_int( &x );
  return 0;
}

That is, a pointer to an rvalue value, but the pointer to itself.

One more example below using string

#include <iostream>

void the_string( const std::string * && ok ){
  std::cout << "Ok: " << *ok << '\n';
}

int main(){
  std::string && ok = "More ok!";
  the_string( &ok );
  return 0;
}

Of course this output will only be the value

I personally don’t see any use for this in the code I create, but this article is for us to know what it means when we see a double ampersand in some code and understand how they are used and what values are returned.

And in summary, as there is in the description of this syntax , C++11 managed to solve the problem of unnecessary copies of C++03 and earlier, but it should be used with care .

That’s all for today, small daily doses that will always keep us in tune with C++!


cpp cppdaily


Share


YouTube channel

Subscribe


Marcos Oliveira

Marcos Oliveira

Software developer
https://github.com/terroo

Related articles