I would like to ask for some advice with regard to exception safety. In particular I have been referencing Do you (really) write exception safe code?. If I have a container of pointers to objects of type Node
, and I were to clear and reinitialise that container of objects _nodes
with a new collection of objects, would this code be exception safe?
std::vector<Node*> nodes;
for (int i = 0; i < 10; i++)
{
try
{
// New can throw an exception. We want to make sure that if an exception is thrown any allocated memory is deleted.
std::unique_ptr<Node> node(new Node());
Node* n = node.get();
nodes.push_back(n);
node.release();
}
catch (std::exception& exception)
{
// If an exception is thrown, rollback new allocations and rethrow the exception.
for (std::vector<Node*>::iterator it = nodes.begin(); it < nodes.end(); it++)
{
delete *it;
}
nodes.clear();
throw exception;
}
}
_nodes.swap(nodes);
// Delete the unused (previous) objects from the swapped container.
for (std::vector<Node*>::iterator it = nodes.begin(); it < nodes.end(); it++)
{
delete *it;
}
I have also been reading into RAII, but I don't know how this would work where I need polymorphism (http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping).