Should my API functions take shared_ptr or weak_ptr

[亡魂溺海] 提交于 2021-01-27 05:04:27

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/48537343/should-my-api-functions-take-shared-ptr-or-weak-ptr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!