I’m rewriting a general purpose library that was written by me before I’ve learned STL. It uses C-style arrays all the way. In many places there is a code like this:
unsigned short maxbuffersize; // Maximum possible size of the buffer. Can be set by user.
unsigned short buffersize; // Current size of the buffer.
T *buffer; // The buffer itself.
The first thing I did was to change the code like this:
unsigned short maxbuffersize;
unsigned short buffersize;
std::vector<T> buffer;
And then:
typedef unsigned short BufferSize;
BufferSize maxbuffersize;
BufferSize buffersize;
std::vector<T> buffer;
And then I felt like I was doing a very bad thing and should reconsider my coding style. At first, BufferSize seemed like a very bad name for a type but then all kinds of weird questions started popping up. How do I name the size type? Should I use my own type or inherit from std::vector<T>::size_type? Should I cache the size of container or use size() all the way? Should I allow the user to manually set the maximum size of container and if not, how do I check for overflow?
I know that there can’t be one-size-fits-all approach therefore I’d like to hear the policies other coders and framework vendors use. The library I’m working on is cross-platform general purpose and is intended to be released into public domain and be used for decades. Thanks.
I think the default choice ought to be to get rid of both
buffersizeandmaxbuffersizeand usebuffer.size()andbuffer.capacity()throughout.I would advise against caching the sizes unless you have very specific reasons to do this, backed with hard data from profiler runs. Caching would introduce extra complexity and the potential for the cache to get of sync with the real thing.
Finally, in places where you feel bounds checking is warranted, you could use
buffer.at(i). This will throw an exception ifiis out of bounds.