简体   繁体   中英

C++ Avoiding excessive use of lock() in member functions that use boost::weak_ptr

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?

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)

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.

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 a Curve is destroyed, remove all objects that depend on it. This way, you don't need any weak_ptr .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM