Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this std::ref behaviour logical?

Tags:

c++

c++11

ref

Consider this code:

#include <iostream> #include <functional>  int xx = 7;  template<class T> void f1(T arg) {     arg += xx; }  template<class T> void f2(T arg) {     arg = xx; }  int main() {     int j;      j=100;     f1(std::ref(j));     std::cout << j << std::endl;      j=100;     f2(std::ref(j));     std::cout << j << std::endl; } 

When executed, this code outputs

107 100 

I would have expected the second value to be 7 rather than 100.

What am I missing?

like image 233
oz1cz Avatar asked May 08 '16 15:05

oz1cz


1 Answers

A small modification to f2 provides the clue:

template<class T> void f2(T arg) {     arg.get() = xx; } 

This now does what you expect.

This has happened because std::ref returns a std::reference_wrapper<> object. The assignment operator of which rebinds the wrapper. (see http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper/operator%3D)

It does not make an assignment to the wrapped reference.

In the f1 case, all is working as you expected because a std::reference_wrapper<T> provides a conversion operator to T&, which will bind to the implicit right hand side of ints implicit operator+.

like image 145
Richard Hodges Avatar answered Sep 19 '22 17:09

Richard Hodges