vector::at vs. vector::operator[]

前端 未结 8 1821
走了就别回头了
走了就别回头了 2020-11-30 18:37

I know that at() is slower than [] because of its boundary checking, which is also discussed in similar questions like C++ Vector at/[] operator sp

8条回答
  •  感动是毒
    2020-11-30 19:10

    First, whether at() or operator[] is slower is not specified. When there's no bounds error, I'd expect them to be about the same speed, at least in debugging builds. The difference is that at() specifies exactly what will happen in there is a bounds error (an exception), where as in the case of operator[], it is undefined behavior—a crash in all of the systems I use (g++ and VC++), at least when the normal debugging flags are used. (Another difference is that once I'm sure of my code, I can get a substantial speed increase for operator[] by turning the debugging off. If the performance requires it—I wouldn't do it unless it were necessary.)

    In practice, at() is rarely appropriate. If the context is such that you know the index may be invalid, you probably want the explicit test (e.g. to return a default value or something), and if you know that it can't be invalid, you want to abort (and if you don't know whether it can be invalid or not, I'd suggest that you specify your function's interface more precisely). There are a few exceptions, however, where the invalid index may result from parsing user data, and the error should cause an abort of the entire request (but not bring the server down); in such cases, an exception is appropriate, and at() will do that for you.

提交回复
热议问题