Search code examples
c++constructorlinked-listnodesdefault-constructor

Avoid needing empty constructor for header node of collection


I have a collection I'm writing which is a form of linked list, but it has a header node. Each node stores an object of template type T. If I didn't need to initialize the header node, then I would not need to require that T has an empty constructor. Furthermore, I never have any reason to look at the object in the header node. Is there some way to leave the memory reserved for that object un-initialized? Then I don't need to require clients to implement an empty constructor.


Solution

  • You could use a union in your nodes and construct the value within only when it is used. Using this approach is sort of midway between allocating the content separately and using a different type for the head node: it would still occopy memory for the unused content but it neither requires an extra allocation/indirection nor a default constructor for the content.