Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do reference_wrapper and std::ref work?

Tags:

c++

c++11

I am trying to understand how std::ref works.

#include <functional>
#include <iostream>

template <class C>
void func(C c){
    c += 1;
}

int main(){
    int x{3};
    std::cout << x << std::endl;
    func(x);
    std::cout << x << std::endl;
    func(std::ref(x));
    std::cout << x << std::endl;
}

Output : 3 3 4

In the code above, I think the template parameter C for the third function call is instantiated as std::reference_wrapper<int>. While reading the reference, I noticed there is no += operator in std::reference_wrapper<int>. Then, how is c += 1; valid?

like image 702
Sungmin Avatar asked May 14 '13 11:05

Sungmin


People also ask

What is std :: reference_wrapper?

std::reference_wrapper is a class template that wraps a reference in a copyable, assignable object. It is frequently used as a mechanism to store references inside standard containers (like std::vector) which cannot normally hold references.

What is the use of reference_wrapper?

A reference_wrapper<Ty> is a copy constructible and copy assignable wrapper around a reference to an object or a function of type Ty , and holds a pointer that points to an object of that type. A reference_wrapper can be used to store references in standard containers, and to pass objects by reference to std::bind .

Can STD pair hold reference?

No, you cannot do this reliably in C++03, because the constructor of pair takes references to T , and creating a reference to a reference is not legal in C++03.


2 Answers

how is c += 1; valid?

Because reference_wrapper<int> is implicitly convertible to int& via its conversion operator; and implicit conversions are considered for operands if there is no suitable overload for the operand type itself.

like image 147
Mike Seymour Avatar answered Oct 11 '22 15:10

Mike Seymour


std::reference_wrapper<T> has a conversion operator to T&. This means that std::reference_wrapper can be implicitly converted to int& in your example.

like image 29
juanchopanza Avatar answered Oct 11 '22 15:10

juanchopanza