Sharath Sharath -4 years ago 221
C++ Question

Passing local variable by reference to a C++ thread

I was reviewing the code of a junior colleague and encountered the following code.

void ActionGetId(boost::property_tree::ptree& callInfo);
void ActionPutId(boost::property_tree::ptree& callInfo);

void handler(int type, std::string data)
boost::property_tree::ptree callInfo(data);
if(type == 0)
{, callInfo);
{, callInfo);

They are passing a local variable by reference and then exit the function. When those functions are finally called, the local variable may not exist. Yet, this program doesn't crash. How is this working?

Answer Source

boost::bind copies the arguments you give it and stores the copies in the function object it returns. When the function is called, it will not act on a reference to the local variable (which no longer exists), but on a reference to the copy (which is still valid).

If you actually wanted boost::bind or std::bind to use a reference to the variable (which you don't want here), you'd need to pass the variable to bind with boost::ref(var) or std::ref(var).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download