2010-04-01 38 views

回答

7

Boost.Ref Documentation

升壓::的reference_wrapper的目的是 包含對 類型T的對象它主要用來「喂」 引用函數模板 基準(算法)按值取其參數 。

NB:boost::reference_wrapperstd::reference_wrapper之間的重要區別(至少升壓1.52的)是std::reference_wrapper完美地包裹功能對象的能力。

這使得這樣的代碼:

// functor that counts how often it was applied 
struct counting_plus { 
    counting_plus() : applications(0) {} 
    int applications; 

    int operator()(const int& x, const int& y) 
    { ++applications; return x + y; } 
}; 

std::vector<int> x = {1, 2, 3}, y = {1, 2, 3}, result; 
counting_plus f; 
std::transform(begin(x), end(x), begin(y), 
       std::back_inserter(result), std::ref(f)); 
std::cout << "counting_plus has been applied " << f.applications 
      << " times." << '\n'; 
+0

@Venkat溼婆:這種情況是「當算法需要的值取它們的參數」和你不想承擔按值傳遞對象的性能損失。 – 2010-04-01 14:47:29

+0

我想我應該在發佈問題前正確閱讀文檔。抱歉,添麻煩了。 – 2010-04-02 05:07:38

4

Boost.Thread例如:

新線程是通過使一個可調用的類型,可以是調用無參數 的 對象啓動到 構造函數。然後將該對象複製到內部存儲器 中,並在 上調用新創建的執行線程。 如果對象不能(或不能)被 複製,那麼可以使用012 :: 0 :: 來傳遞 通過函數 對象的引用。在這種情況下, Boost.Thread的用戶必須確保引用對象超出了新創建的執行線程。從文檔

代碼:

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 
相關問題