jeudi 27 avril 2023

How to implement the Builder Design Pattern with the use of smart pointers?

I want to implement the builder pattern in C++ for a project that I am working on. I have found plenty of examples of this design pattern that uses raw pointers, but none that uses smart pointers. Since my opinion is that smart pointers are the way to go when writing modern C++ code, I wonder how the builder pattern can be implemented with the use of smart pointers for the director, builder, product et cetera.

I use the conceptual example code of Refactoring.Guru for the C++ builder design pattern as reference: https://refactoring.guru/design-patterns/builder/cpp/example.

How can I transform this conceptual example into a modern C++ builder pattern with the usage of smart pointers? I understand that where raw pointers are present, you can replace them with smart pointers, but i am mostly struggling with where to use unique pointers and shared pointers and how to pass them from function to function. Do I use unique pointers and just move them in every function call or do I use shared pointers in the case of the product for example?

It's a shame Refactoring.Guru does not include such a version of this example.

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire