I have a template container class, something like this toy code:
template <class ItemType> class MyVector { public: MyVector() : _numItems(0), _items(NULL) {} const ItemType & GetFirstItemWithDefault() const { return (_numItems > 0) ? _items[0] : _defaultItem; } [other methods omitted because they aren't relevant] private: int _numItems;
This class is really convenient to use - any code can simply # include "MyVector.h" and then start declaring objects like MyVector and MyVector, etc., and all this is Just Works (tm) without any distortion around the required one.
However, one thing that bothers me is the presence of the _defaultItem member variable, which should only give GetFirstItemWithDefault () the ability to return a valid link when the container is empty. The objection is that if I declare N MyVector objects, this means that there will also be N copies of _defaultItem in RAM - even if they are all the same and read-only, and therefore in fact there should be only one of them The process is not alone on MyVector.
So, the obvious solution is to make _defaultItem static .... but AFAICT, which comes with a cost: if I do this, it is no longer possible for any old code snippet to just include โMyVector.hโ and go. .. now the user must necessarily declare storage for this static variable in one of his .cpp files, which is (a) a pain in the butt, and (b) means that the user of the code has to be aware of the details of the internal implementation of the class. Since _defaultItem is a private member variable, the class user should not think about it or even realize that it exists, not to mention that it needs to declare a repository for it. (and what if two separate code snippets declare a repository for it, each of which does not know the other, does the same? Does this not lead to a duplicate symbol character error?)
So my question is: is there a way to tell C ++ to automatically provide one unique store (for each instance of MyVector) for this static member variable so that MyVector users are not aware of this? (Note that it should be automatic for all possible instances of MyVector <...>, and not just for a few common cases)
Jeremy friesner
source share