Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is tr1::reference_wrapper useful?

Tags:

recently I've been reading through Scott Meyers's excellent Effective C++ book. In one of the last tips he covered some of the features from TR1 - I knew many of them via Boost.

However, there was one that I definitely did NOT recognize: tr1::reference_wrapper.

How and when would I use tr1::reference_wrapper?

like image 995
paxos1977 Avatar asked Oct 11 '08 05:10

paxos1977


People also ask

What is the use of std :: ref?

std::ref. Constructs an object of the appropriate reference_wrapper type to hold a reference to elem . If the argument is itself a reference_wrapper (2), it creates a copy of x instead. The function calls the proper reference_wrapper constructor.

What does REF do in C++?

References in C++ When a variable is declared as a reference, it becomes an alternative name for an existing variable. A variable can be declared as a reference by putting '&' in the declaration.


1 Answers

It's like boost::ref, as far as I know. Basically, a reference which can be copied. Very useful when binding to functions where you need to pass parameters by reference.

For example (using boost syntax):

void Increment( int& iValue ) {     iValue++; }  int iVariable = 0; boost::function< void () > fIncrementMyVariable = boost::bind( &Increment, boost::ref( iVariable ));  fIncrementMyVariable(); 

This Dr. Dobbs article has some info.

Hope this is right, and helpful. :)

like image 83
Nick Avatar answered Oct 08 '22 18:10

Nick