考慮下面的代碼:lambda函數中引用/值的捕獲成本?
#include <iostream>
#include <algorithm>
#include <numeric>
int main()
{
const unsigned int size = 1000;
std::vector<int> v(size);
unsigned int cst = size/2;
std::iota(v.begin(), v.end(), 0);
std::random_shuffle(v.begin(), v.end());
std::cout<<std::find_if(v.begin(), v.end(), [&cst](const int& i){return i == cst;})-v.begin()<<std::endl;
std::cout<<std::find_if(v.begin(), v.end(), [=](const int& i){return i == cst;})-v.begin()<<std::endl;
return 0;
}
此代碼填充一個矢量與值,打亂它然後搜索指定的值的索引(它只是爲了說明我的問題的示例)。該值cst
可以通過引用或通過lambda函數中的值捕獲。
我的問題:這兩個版本在性能上有差異,還是它們會被編譯器以相同的方式進行優化?
是一個很好的規則,通過引用(如在正常函數中)通過值和常量類傳遞常量基本類型?
Vincent是任何人對您滿意的答案 – aaronman
我知道您已經接受了答案,但需要考慮的一件有趣事情是,通過值捕獲是默認常量,這意味着它可以輕鬆地優化複製整個obj,因爲它不會被更改 – aaronman