6

Consider the following code:

#include <iostream>
#include <functional>

using namespace std;

template<class T>
void fun(T t) 
{ 
    t+=8;
}


int main()
{
    int i = 0;
    fun(ref(i));
    cout << i << endl;
}

This code prints "8". I assume that the t in fun() is automatically converted to an int&.

But if I replace t+=8 with t=8, the program will not compile.

Why?

1 Answer 1

4

reference_wrapper<T> has an implicit conversion operator to T &, so it will be converted to T & wherever a T & is a better match than a reference_wrapper<T>.

In the augmented assignment expression, the only viable operator is int &operator+=(int &, int) so the int & is extracted.

In the assignment expression, the member operator reference_wrapper<int>::operator=(const reference_wrapper<int> &) is also available, so the member operator is preferred; the compiler then attempts to construct a reference wrapper from the constant 8, which fails. The assignment operator has the effect of rebinding, which is necessary for facilities like tie to work as expected.

This means that reference wrappers are closer to references in languages like Python than C++ references:

#include <functional>
#include <iostream>

int main() {
    int i = 1, j = 2;
    std::ref(i) = j;
    std::cout << i << '\n';                 // prints '1'
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.