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

前端 未结 13 2131
清酒与你
清酒与你 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:04

    If what you need is some sort of "circular" array of points, then your solution is ok. However, to me, it looks just like hiding missusage of indexing operator behind some "safe" logic, so I would be against your proposed solution.

    If don't want to allow index overflow, then you could check and throw an exception.

    quint16 curvePoint::operator[](size_t index)
    {
        if( index >= dimensions)
        {
           throw std::overflow_error();
        }
        return point[ index ];
    }
    

    If you want to have less overhead, you could avoid exception, by using debug time assertions (assume that the provided index is always valid):

    quint16 curvePoint::operator[](size_t index)
    {
        assert( index < dimensions);
        return point[ index ];
    }
    

    However, I suggest that, instead of using point and dimension members, use a std::vector< quint16> for point storage. It already has an index based access that you could use:

    quint16 curvePoint::operator[](size_t index)
    {
        // points is declared as std::vector< quint16> points;
        return points[ index ];
    }
    

提交回复
热议问题