shared, weak and lazy pointers in C++

感情迁移 提交于 2019-12-03 11:53:47

问题


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:


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.



来源:https://stackoverflow.com/questions/8362513/shared-weak-and-lazy-pointers-in-c

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