Question

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.

Was it helpful?

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.

OTHER TIPS

I assume you are aware of std::list and std::forward_list. If so and you still want to write you're own linked list to get the behaviour you want your best bet is to use std::aligned_storage in conjunction with placement new.

Or if you have access to boost, you can just delete that responsibility to boot::optional.

http://en.cppreference.com/w/cpp/types/aligned_storage

http://www.boost.org/doc/libs/1_55_0/libs/optional/doc/html/index.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top