shared, weak and lazy pointers in C++

2019-03-15 07:14发布

Is anyone aware of an implementation of shared_ptr and weak_ptr together with a lazy initialization partner? The requirements of the classes were:

  • A lazy_ptr class that allows a client to construct the object later (if at all), without needing the constructor implementation

  • A weak_lazy_ptr class that has three possible states: not yet constructed (won't lock to a shared_ptr), constructed (will lock to a shared_ptr) and destroyed (won't lock to a shared_ptr)

I created some classes that didn't do the job completely a while ago (see CVu article here) that used shared_ptr and weak_ptr in their implementation. The main problems with a model that USES shared and weak pointers instead of integrating with them follow:

  1. Once all lazy_ptr objects go out of scope, any weak references can no longer be locked, even if other clients are holding shared_ptr versions

  2. Construction of objects on different threads can't be controlled

I'd appreciate any pointers to other attempts to reconcile these problems, or to any work in progress there may be in this area.

1条回答
家丑人穷心不美
2楼-- · 2019-03-15 07:53

To create deferred construction that requires no parameters:

boost::bind( boost::factory<T*>(), param1, param2 ) will create a function object that performs the equivalent of new T(param1, param2) without needing the parameters at the time of construction.

To create a shared_ptr that supports this deferred construction:

Bundle your factory with the standard boost::shared_ptr (in a class of your creation, for example), and you'llget the results you describe, including the appropriate weak_ptr functionality...

Whatever code triggers the deferred construction by the client should run:

your_shared_ptr.reset( your_factory() );

Whatever code triggers the object's destruction should run:

your_shared_ptr.reset();

The shared pointer will evauluate to true only during the object's lifetime. And if you want you differentiate "not yet constructed" from "destroyed", you can set a bool after the factory is run.

查看更多
登录 后发表回答