在下面的for循环内的两个lambda中,专家(或至少比I高的专家)建议使用“j”索引,该索引在第二个循环中显示。我想了解为什么在功能上输出没有区别。

我的可执行程序在Github上here上。

for(int j = 0;j<recPtr->numThreads;j++){

    recPtr->heads[j] = 0;
    recPtr->tails[j] = 0;
    headsPtr = &recPtr->heads[j]; // Get the address of the index of the array, one element for each thread for heads.
    tailsPtr = &recPtr->tails[j]; // Get the address of the index of the array, one element for each thread for heads.

    threads.push_back(thread([headsPtr, tailsPtr, timesToToss]()
    {
        for(int k=0;k<timesToToss;k++)
        {
            if (Tosser(dre)) ++(*headsPtr);
            else ++(*tailsPtr);
        }
    })); //Toss a coin!
}


for (int j = 0; j < recPtr->numThreads; j++)
{

    recPtr->heads[j] = 0;
    recPtr->tails[j] = 0;
    headsPtr = &recPtr->heads[j]; // Get the address of the index of the array, one element for each thread for heads.
    tailsPtr = &recPtr->tails[j]; // Get the address of the index of the array, one element for each thread for heads.

    threads.push_back(thread([j, headsPtr, tailsPtr, timesToToss]()
    {
        for(int k=0;k<timesToToss;k++)
        {
            if (Tosser(dre)) ++(*headsPtr);
            else ++(*tailsPtr);
        }
    })); //Toss a coin!
}

最佳答案

lambda不使用j,因此没有理由捕获它。它没有给您带来任何好处。

但是,您通过使用int来使闭包更大,从而产生了额外的int副本,并且使您的代码(包括您自己)的 future 查看者感到困惑,他们可能会怀疑以前的代码迭代是否需要j

因此,请勿捕获j

关于c++ - Lambda函数C++:捕获循环索引是否有所作为?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37083308/

10-11 22:06
查看更多