Michael
Michael

Reputation: 35

Why does using auto and int give different answers in this code?

I am assigning 2 variables the values of 10. When i use ref() on one of those variables using "int", i get a different value and when i use "auto", i get a different value.

Using auto

     int foo(10);
     auto bar = std::ref(foo);
     ++bar; 
     cout << foo << endl;
     std::cout << bar << endl << endl;

Output: 11
        11
Using int

     int boo(10);
     int jar;
     jar = std::ref(boo);
     ++jar;
     std::cout << boo << '\n';
     std::cout << jar << '\n';

Output: 10 (why does this not increment?)
        11

Upvotes: 1

Views: 86

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409176

The std::ref function creates a std::reference_wrapper object. This object wraps a reference to foo.

With

auto bar = std::ref(foo);

you basically creates (in an indirect way) a reference to foo, and in that first example all modifications to bar will be made to foo. It's equivalent to

std::reference_wrapper<int> bar = std::ref(foo);

and behaves basically like a plain reference:

int& bar = foo;

In the second example you also create such a reference wrapper object, but then you take its value and copy it into the variable jar. The reference wrapper object is then destructed. All modifications to jar are only done to the variable jar itself, not to foo.

Upvotes: 2

BiagioF
BiagioF

Reputation: 9715

The utility std::ref returns an object of type std::reference_wrapper.

Therefore, in your example:

auto bar = std::ref(foo);

The type of bar will exactly be std::reference_wrapper. In short, it will behave as a reference, so the effect of the statement ++bar; will increase the value of the referenced variable (i.e., foo).

On the other hand, in the statement:

int jar = std::ref(boo);

jar as type int. Note: that is not a reference, rather a completely new variable named jar. When you increment jar, that won't affect the other variable (foo).


Additional Notes:

For sake of completeness, the statement int jar = std::ref(boo); hides an implicit cast. Indeed, the object std::reference_wrapper can be implicitly casted into a T&.

Upvotes: 4

Related Questions