I would like to implement a builder pattern in modern C ++. Based on the Java background, this is what I would like to emulate:
FooBuilder builder;
builder.setArg1(a);
builder.setArg2(b);
Foo foo = builder.build();
public class FooBuilder {
public Foo build() {
return new Foo(a, b);
}
}
Typical old tutorials are simply advised to do this as in C ++:
class FooBuilder {
Foo* build() {
return new Foo(m_a, m_b);
}
}
which is obviously not a good idea, as working with raw pointers can be error prone. The best I have used so far is to use it std::unique_ptrmanually:
class FooBuilder {
std::unique_ptr<Foo> build() {
return std::make_unique<Foo>(m_a, m_b);
}
}
auto fooPtr = builder.build();
Foo& foo = *fooPtr;
foo.someMethod();
This is better since it doesn't require manual delete, this two-line conversion to a link is ugly, and more importantly, it uses heap allocation, while a simple version without a linker will be completely fine with just a simple stack distribution:
Foo foo(..., ...);
, unique_ptr - Foo?