jeudi 1 octobre 2015

exception safety with smart pointers

I have a situation where passing ownership of a raw pointer may throw an exception. There are several such blocks, and it would be inelegant to wrap each in a try/catch just to delete pointers which weren't accepted. Instead I'm using a unique_ptr<A> to manage my pointer with RAII:

unique_ptr<A> a(new A());
obj.take(a.get()); // pass ownership to obj, might throw
a.release(); // release pointer since obj is now responsible

So the idea behind this is to keep ownership of the raw pointer in the current function until it has been successfully passed to somebody.take(). This seems like a very nice pattern to me, but is it really? Any pitfalls I'm overlooking?

Aucun commentaire:

Enregistrer un commentaire