且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我应该在代码中使用std :: vector :: at()吗?

更新时间:2022-06-17 05:49:05

如果您有理由相信索引不在您的控件中,或者如果控件流程特别复杂并且您正在跟踪错误,那么您可能会希望在调试阶段使用at(),但切勿在循环内或任何您知道索引安全的情况下使用.

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.

即使在其他情况下,您也应该预先验证索引(例如,如果是用户输入),或者如果您只是从复杂算法中获取值,请使用assert并修复存在的错误. 或者,如果您正在编写一个非常复杂的算法,并且不确定所有索引是否始终有效,则可以在该算法内部使用at()并将调用放入尝试阻止-但即使在这种情况下,***还是冒犯并与断言一起使用.[/]

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. 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.[/]

就我个人而言,我看不到at()能够生存到发行代码中的任何充分理由.您可能会想到一些示例,这些示例中您想使用异常处理作为指导控制流的便捷方法,但是任何此类用例都是非常实际的情况.

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.