我的 API 函数应该采用 shared_ptr 还是 weak_ptr
我目前正在设计一个 API,我不确定我的函数应该采用 shared_ptr
还是 weak_ptr
.有包含查看器的小部件.查看器有一个函数 add_painter
可以向查看器添加一个画家.当查看器需要重绘时,它使用它的画家来绘制到缓冲区中并显示结果.我得出的结论是,观众应该使用 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
:
- 一个画家可能会在多个查看者中使用,因此查看者不能拥有该画家.
- 删除画家应将其从查看器中移除.这样,用户就不需要记住他们必须调用
remove_painter
函数.
可能有不同类型的查看器,因此它们隐藏在界面后面.什么签名最适合界面中的 add_painter
函数?
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?
是否应该直接使用void add_painter(weak_ptr
?这意味着具体实现使用 weak_ptr
存储画家,但我不能强制执行:一个实现可以只执行 painters.push_back(weak_ptr.lock())
并存储一个shared_ptr
.
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
.
我应该使用 void add_painter(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?
你不应该试图用智能指针来缓解观察者模式,你绝对应该避免客户端(视图)可以通过转换弱指针来骚扰服务器的情况指向共享指针的指针并无限期地存储它以防止服务器释放它.
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.
您应该真正考虑这里的经典观察者模式,它要求 View 提供一个 painter_destroyed
回调函数.这可能会很烦人,但也让客户有机会在画家被摧毁后实施一些额外的行动.否则发现画家不再只是在人们想要使用它时才存在可能会很烦人并影响整体程序性能.
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.