例外の安全性に関してアドバイスをお願いしたいと思います。特に、私は参照していますDo you (really) write exception safe code? . タイプ のオブジェクトへのポインターのコンテナーがあり、そのオブジェクトの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 )。