开发者

Temporary function object in a for loop

Does the function object randomElementByWeight constructor get called for every iteration through the loop or can the compiler optimize this away somehow? I want to make sure the rand function is called for each iter开发者_运维技巧ation and I think it's nicer to have it in the function object constructor.

struct randomElementByWeight
{
    double randomNumber;

    randomElementByWeight() : randomNumber(rand() / static_cast<double>(RAND_MAX)) {}

    bool operator()(const Element& e)
    {
        if ( (randomNumber -= e.weight) <= 0.0 )
        {
            return true;
        }

        return false;
    }
};

...

for (int i = 0; i < 3; ++i)
{
    iter = find_if(routes.begin(), routes.end(), randomElementByWeight());
}


Yes it does, a constructor is always called for a temporary variable. Unless the compiler knows absolutely sure there are no side-effects if ommitted it won't optimize it away.


Just a side note, the following code:

if ( (randomNumber -= e.weight) <= 0.0 )
{
    return true;
}

return false;

can be abbreviated to:

return (randomNumber -= e.weight) <= 0.0;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜