I am currently designing an API and I am not sure whether my functions should take shared_ptr
or weak_ptr
. There are widgets that contain viewers. The viewers have a function add_painter
which adds a painter to the viewer. When a viewer needs to redraw, it uses its painters to draw into a buffer and displays the result. I came to the conclusion that the viewers should hold the painters using weak_ptr
:
- A painter may be used in multiple viewers, so the viewer cannot own the painter.
- Deleting the painter should remove it from the viewer. This way, users do not need to remember that they have to call a
remove_painter
function.
There may be different kind of viewers, so they are hidden behind an interface. What signature is best for the add_painter
function in the interface?
Should I directly use void add_painter(weak_ptr<Painter> const& p)
? This implies that the concrete implentations store the painters using weak_ptr
, but I cannot enforce this: An implementation could just do painters.push_back(weak_ptr.lock())
and store a shared_ptr
.
Should I use void add_painter(shared_ptr<Painter> const& p)
instead? This implies that the viewers hold strong references, so that deleting a painter does not necessarily remove it from the viewer.
I also considered storing the painters directly in the interface class, but then it is no real interface anymore, is it?