I’m trying to implement an index that I want to use to handle the nodes I encounter as I parse an xml document. I’ve been reading about smart pointers and was wondering how I might modify the below code so that it uses safer pointer management. Should I use unique_ptr for the Descriptor nodes? Should I return shared_ptr from the create() methods? Is there a way to do this without pointers? (The virtual members seem to prevent me from passing things by reference)
Is using smart pointers here overkill and I should just use raw pointers?
Any feedback on the design of the below code would be appreciated.
Your code will produce undefined behavior when derived class is being deleted because base class destructor will be called!
This is true even if deleting derived class trough base class pointer, in both cases base class destructor is called but has no implementation.
virtual Node* build() = 0;
this is bad, because even if the destructor is pure virtual you need to implement it, otherwise UB will happen in above mentioned cases.
Thanks for your suggestion, JLBorges - this looks like the best way to clean up what I wrote.
You asked if pointers and a hierarchy must be used, and my answer is I'm not sure. Using inheritance for the Node classes makes sense to me, since each node type refines the behavior of a more general node. The rest is just a means to an end. I need a way for my program to use some sort of token to refer to the different node types and create them on demand. Is there a way to design this with less reliance on pointers?
> I need a way for my program to use some sort of token to refer to the different node types
> and create them on demand. Is there a way to design this with less reliance on pointers?
No really convenient way to do that without dynamic object creation; use smart pointers.
Here is a somewhat more stylised (idiomatic C++) version of the same.
(For brevity, in this toy example, all functions are implemented inline, with everything in one source file.)