vendredi 15 novembre 2019

Does using an initializer list in a loop work? If not, how does it fail and why?

The answers to this question imply that using an initializer list in a loop or with "unknown data" wouldn't work. They don't say why, or how it would fail.

IE, doing this: (this is a nonsense operation, but shows that the contents of the list would change as the loop progresses)

std::vector<float> vec;
// Assume vec is filled with some useful data

for(int i = 0; i < 10; i++) 
{ 
  for(int j = 0; j < 10; j++) 
  {
    for(int k = 0; k < 10; k++) 
    {
      result = std::max({vec[i], vec[j], vec[k]});
      // do something with result...
    }
  }
}

I have code that uses initializer lists to get the max of 3 or more elements very frequently. It seems like things are working, but I am not sure if they are or not.

I'd like to understand if it works. If not, how it fails and why.

I've used a very heavy set of warnings, nothing has ever reported "warning: may be using initializer list incorrectly" or so-on.

Aucun commentaire:

Enregistrer un commentaire