Search code examples
c++shared-ptrweak-ptr

Should my API functions take shared_ptr or weak_ptr


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?


Solution

  • You should not try to mitigate the Observer pattern with smart pointers and definitely you should avoid a situation when a client (View) can harass the server by converting the weak pointer to a shared pointer and storing it indefinitely barring it from being released by the server.

    You should really consider the classic Observer pattern here requesting View to provide a painter_destroyed callback function. It may be an annoyance but also gives the client an opportunity to implement some additional actions once the painter is destroyed. Otherwise finding that the painter exists no more just when one wants to use it may be quite irritating and affect overall program performance.