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

前端 未结 13 2192
清酒与你
清酒与你 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 07:06

    Unless I'm drastically misunderstanding something,

    return point[ index % dimensions ];
    

    is not bounds checking at all. It's returning a real value from a totally different part of the line, which will make it much harder to detect bugs.

    I would either:

    1. Throw an exception or an assertion (though you said you don't want to do so)
    2. Simply dereference point past the array in a "natural" way (i.e. just skip any internal checking). The advantage over the % is that they're more likely (though undefined is undefined) to get "weird" values and/or an access violation

    In the end, the caller is violating your pre-conditions, and you can do whatever you please. But I think these are the most reasonable options.

    Also consider what Cătălin said about incorporating built-in STL collections if that's reasonable.

提交回复
热议问题