When implementing operator[] how should I include bounds checking?

前端 未结 13 1950
清酒与你
清酒与你 2021-01-19 06:12

First of all I apologize for the long lead up to such a simplistic question.

I am implementing a class which serves as a very long 1 dimensional index on a space fil

13条回答
  •  走了就别回头了
    2021-01-19 06:46

    The easiest solution is to do as C++ itself does. This limits the amount of surprises that your users will experience.

    C++ itself is fairly consistent. Both the built-in [] on pointers and std::vector::operator[] have undefined behavior if you use an out-of-bound array index. If you want bounds checking, be explicit and use std::vector::at

    Hence, if you do the same for your class, you can document the out-of-bound behavior as "standard".

提交回复
热议问题