Should I use std::vector::at() in my code

前端 未结 6 2397
感动是毒
感动是毒 2021-02-19 02:17

I noticed today that std::vector::at() is significantly slower than accessing values with square brackets []. According to the doc .at() i

6条回答
  •  抹茶落季
    2021-02-19 02:48

    If you have reason to believe that the index is not in your control, or if the control flow is particularly complicated and you're tracing bugs, then you might want to use at() during the debug phase, but never inside loops or any situation where you know that the index is safe.

    Even in other situations you should either prevalidate the index (e.g. if it's user input), or if you are just getting the value from a complicated algorithm, use assert and fix the bug if there is one. [Edit.] Or perhaps if you are writing a very complicated algorithm and you aren't sure that all your indices are always valid, you could use at() inside that algorithm and put the call into a try block -- but even here it is preferable to be offensive and use with assertions.[/]

    Personally, I can't see any good reasons for at() to survive into release code. You could possibly contrive some examples where you want to use exception handling as a convenient way to direct your control flow, but any such use case would be very situational.

提交回复
热议问题