0

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 iteration 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());
}
ephi
  • 41
  • 2

2 Answers2

2

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.

orlp
  • 112,504
  • 36
  • 218
  • 315
0

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;
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
  • I get a warning when I do that warning MS VS2008 C4800: 'double' : forcing value to bool 'true' or 'false' (performance warning) – ephi Jul 14 '11 at 18:51
  • @ephi: Impossible, the `<=` operator yields a bool. Did you forget the parenthesis or something? – fredoverflow Jul 14 '11 at 19:29
  • yup. I must have missed something. I tried it again and its ok – ephi Jul 14 '11 at 20:39