boost::ref(i)
和& i
之間的區別是什麼?有什麼情況我們不能使用常規的參考文獻,而是必須改爲boost::ref
?請儘可能包含示例。boost :: ref和常規參考之間的區別
9
A
回答
7
升壓::的reference_wrapper的目的是 包含對 類型T的對象它主要用來「喂」 引用函數模板 基準(算法)按值取其參數 。
NB:boost::reference_wrapper
和std::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';
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
相關問題
- 1. object_id和常規ID之間的區別
- 2. boost :: mutex和boost :: timed_mutex之間的區別
- 3. 'const ref'和'in'之間的區別?
- 4. 短弱參考和長弱參考之間有什麼區別?
- 5. boost async_write()和non_blocking之間的區別socket.send()
- 6. boost shared_ptr:operator =和reset之間的區別?
- 7. std :: array和boost :: array之間的區別
- 8. 規範和政策之間的區別?
- 9. 參數和參數之間的區別
- 10. {參數}和參數之間的區別?
- 11. 參考,模板和NuGet包之間的區別?
- 12. 類參考和類實例之間的區別
- 13. Simulink庫和模型參考之間的區別
- 14. C#參考類型和「可變」概念之間的區別?
- 15. 的Gemfile:差異分支和REF之間在GitHub的參考
- 16. jquery函數和常規javascript函數之間的區別?
- 17. AJAX請求和常規瀏覽器請求之間的區別
- 18. SQL Plus和「常規」SQL之間的區別?
- 19. boost :: chrono :: time_point <>和boost :: chrono :: steady_clock :: time_point之間的區別
- 20. 變量賦值和傳遞參考之間有什麼區別?
- 21. 對象表的RowID和REF之間的區別表
- 22. 異常和錯誤之間的區別
- 23. 異常和錯誤之間的區別?
- 24. valgrind和常規C++運行之間有什麼區別
- 25. 「常規」和「讀者」宏之間有什麼區別?
- 26. 「原子交換!」之間的區別和「ref commute」
- 27. C++/CLI ref類和C#類之間的區別
- 28. Ref對象的getPeeledObjectId()和getObjectId()之間有什麼區別?
- 29. const ref和const指針之間的區別,C++
- 30. 可衍生規則和可允許規則之間的區別?
@Venkat溼婆:這種情況是「當算法需要的值取它們的參數」和你不想承擔按值傳遞對象的性能損失。 – 2010-04-01 14:47:29
我想我應該在發佈問題前正確閱讀文檔。抱歉,添麻煩了。 – 2010-04-02 05:07:38