Question

I have an object created from a builder. After doing some stuff I have to delete it. But the code will not be reached if an, exception is thrown

{
  cClass* cc = MyBuilder.build();
  // do something usefull, exception may be thrown
  delete cc;
}

Since there is no finally keyword in C++ like in Java, Resource Acquisition Is Initialization is the way to go. Right?

So, how do I implement the Builder pattern using Resource Acquisition Is Initialization?

Was it helpful?

Solution

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top