我想请教一些关于异常安全的建议。特别是我一直在参考你(真的)写异常安全代码吗?. 如果我有一个指向类型对象的指针容器Node
,并且我要使用新的对象集合清除并重新初始化该对象容器_nodes
,那么这段代码是否是异常安全的?
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;
}
我也一直在阅读 RAII,但我不知道这在我需要多态性的情况下如何工作(http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping)。