Using operator[] on empty std::vector

前端 未结 7 920
迷失自我
迷失自我 2021-01-12 05:29

I was advised a while ago that is was common place to use std::vector as exception safe dynamic array in c++ rather than allocating raw arrays... for exampl

相关标签:
7条回答
  • 2021-01-12 06:34

    operator [] returns a reference, and therefor invoking it on an empty vector must be undefined.

    After all, which item should the reference refer to, when there are no items? operator [] would have to return a null-reference or a totally invalid reference. Both of which would result in undefined behavior.

    So yes, you were using undefined behavior all along. Visual Studio's not-mandatory-but-still-comformant checks in operator [] just revealed that fact.

    0 讨论(0)
提交回复
热议问题