views:

248

answers:

2

What is the difference between boost::ref(i) and & i ? What are the situations where we cannot use regular references and have to go for boost::ref instead? Please include examples if possible.

+4  A: 

From the Boost.Ref Documentation:

The purpose of boost::reference_wrapper is to contain a reference to an object of type T. It is primarily used to "feed" references to function templates (algorithms) that take their parameter by value.

pmr
@Venkat Shiva: The situation is "When algorithms need to take their parameter by value" and you do not want to incur the performance penalty of passing an object by value.
Billy ONeal
I guess I should read the documentation properly before posting the questions. Sorry for the trouble.
Venkat Shiva
+1  A: 

In Boost.Thread for example :

A new thread is launched by passing an object of a callable type that can be invoked with no parameters to the constructor. The object is then copied into internal storage, and invoked on the newly-created thread of execution. If the object must not (or cannot) be copied, then boost::ref can be used to pass in a reference to the function object. In this case, the user of Boost.Thread must ensure that the referred-to object outlives the newly-created thread of execution.

Code from doc :

struct callable
{
    void operator()();
};

boost::thread copies_are_safe()
{
    callable x;
    return boost::thread(x);
} // x is destroyed, but the newly-created thread has a copy, so this is OK

boost::thread oops()
{
    callable x;
    return boost::thread(boost::ref(x));
} // x is destroyed, but the newly-created thread still has a reference
  // this leads to undefined behaviour
anno