Should I use std::for_each?

前端 未结 9 1318
自闭症患者
自闭症患者 2020-12-08 04:18

I\'m always trying to learn more about the languages I use (different styles, frameworks, patterns, etc). I\'ve noticed that I never use std::for_each so I thought that perh

9条回答
  •  粉色の甜心
    2020-12-08 04:30

    Note that the "traditional" example is buggy:

    for(int i=0; i

    This assumes that int can always represent the index of every value in the vector. There are actually two ways this can go wrong.

    One is that int may be of lower rank than std::vector::size_type. On a 32-bit machine, ints are typically 32-bits wide but v.size() will almost certainly be 64 bits wide. If you manage to stuff 2^32 elements into the vector, your index will never reach the end.

    The second problem is that you're comparing a signed value (int) to an unsigned value (std::vector::size_type). So even if they were of the same rank, when the size exceeds the maximum integer value, then the index will overflow and trigger undefined behavior.

    You may have prior knowledge that, for this vector, those error conditions will never be true. But you'd either have to ignore or disable the compiler warnings. And if you disable them, then you don't get the benefit of those warnings helping you find actual bugs elsewhere in your code. (I've spent lots of time tracking down bugs that should have been detected by these compiler warnings, if the code had made it feasible to enable them.)

    So, yes, for_each (or any appropriate ) is better because it avoids this pernicious abuse of ints. You could also use a range-based for loop or an iterator-based loop with auto.

    An additional advantage to using s or iterators rather than indexes is that it gives you more flexibility to change container types in the future without refactoring all the code that uses it.

提交回复
热议问题