我有一个名为 Curve
的抽象基类。从它继承了三个类:
- 单曲线
- 多曲线
- CurveShift
,它“移动”从 Curve
派生的任何内容(在其构造函数中采用 boost::shared_ptr
)
我有一个内存中跟踪所有曲线的存储库,我们称之为 CurveStore。它是作为带有 std::map 的单例实现的。 >
里面。
我的问题出在 CurveShift
上。我想使用 boost::weak_ptr
来引用它正在移动的底层Curve
。这样,如果底层 Curve
消失,CurveShift
将无法获得 lock()
并且我会知道 < code>CurveShift 无效。问题在于,在 CurveShift 的简单实现中,每次访问成员函数之一时都尝试获取 lock()
,这会显着降低性能。是否有一种标准方法/“模式”来避免在所有成员函数中执行 lock()
?
I have an abstract base class called Curve
. There are three classes that inherit from it:
- SingleCurve
- MultiCurve
- CurveShift
, which "shifts" anything that derives from Curve
(takes a boost::shared_ptr<Curve>
in its constructor)
I have a repository in memory that keeps track of all the curves, let's call it CurveStore
. It is implemented as a singleton with a std::map<std::string, boost::shared_ptr<Curve> >
inside of it.
My problem is with CurveShift
. I want to use a boost::weak_ptr
to reference the underlying Curve
it is shifting. This way, should the underlying Curve
go away, the CurveShift
will not be able to get a lock()
and I will know that the CurveShift
is invalid. The problem is that in the naive implementation of CurveShift
, where you try to get a lock()
every time you access one of the member functions, it degrades performance significantly. Is there a standard way/"pattern" to avoid having to do a lock()
in all the member functions?
发布评论
评论(2)
“模式”将是“外部/内部函数”(不是官方名称),其中外部函数(公共)锁定weak_ptr,内部函数(私有)采用shared_ptr&作为参数。仅当您拥有一个真正让对象执行某些操作的精益接口(而不是 getter/setter 接口)时,这才会有帮助
The "pattern" would be "external/internal functions" (not an official name), where the external functions (public), lock the weak_ptr's and the internal functions (private) take a shared_ptr& as parameter. This only helps if you have a lean interface that actually lets the object do something (not a getter/setter interface)
设计非常奇怪且薄弱。 (但是大多数基于weak_something的设计都很奇怪,而且很弱。)
你真的想要这种弱行为吗?
我建议您将设计更改为不包含 null
CurveShift
对象:每当Curve
被销毁时,请删除依赖于它的所有对象。这样,您就不需要任何weak_ptr
。Very strange, and weak, design. (But most designs based on weak_something are strange, and weak.)
Do you really want this weak behaviour?
I suggest that you change your design to not have null
CurveShift
object: whenever aCurve
is destroyed, remove all objects that depend on it. This way, you don't need anyweak_ptr
.