The MyBuilder
should return either a unique_ptr
or a shared_ptr
, depending on if it wants to hold a reference to the returned pointer itself. This will not only provide the desired exception safety but also help if for some reason the builder has to destroy the objects it created later on:
class MyBuilder {
std::shared_ptr<MyClass> build() {
return std::shared_ptr<MyClass>{new MyClass(), [this](MyClass* ptr){ destroy(ptr); } };
}
void destroy(MyClass* ptr) {
/* do something with ptr */
delete ptr;
}
};
//later:
{
auto ptr = myBuilder.build();
} //automatically calls myBuilder.destroy(ptr)