簡體   English   中英

通過引用將局部變量傳遞給C ++線程

[英]Passing local variable by reference to a C++ thread

我正在查看一個初級同事的代碼,並且遇到了以下代碼。

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)
    {
        _ioService.post(boost::bind(&ActionGetId, callInfo);
    }
    else
    {
        _ioService.post(boost::bind(&ActionPutId, callInfo);
    }
}

他們通過引用傳遞局部變量,然后退出函數。 當這些函數最終被調用時,局部變量可能不存在。 但是,該程序不會崩潰。 這如何運作?

boost::bind復制您提供的參數,並將副本存儲在返回的函數對象中。 調用該函數時,它不會作用於對局部變量的引用(不再存在),而是作用於對副本的引用(仍然有效)。

如果您實際上希望boost::bindstd::bind使用對變量的引用(在此處不需要),則需要傳遞變量以與boost::ref(var)std::ref(var) bind std::ref(var)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM