共享,弱和惰性指针 [英] shared, weak and lazy pointers in C++
问题描述
有人知道 shared_ptr
和 weak_ptr
的实现与懒惰的初始化合作伙伴吗?类的要求是:
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
A weak_lazy_ptr
类有三种可能的状态:尚未构建(不会锁定到 shared_ptr
),构造(将锁定到 shared_ptr
)并销毁(不会锁定到 shared_ptr
)
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
)
我创建了一些类,完成前一段时间没有完成这项工作(请参阅CVu文章)在其实现中使用 shared_ptr
和 weak_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:
-
一旦所有
lazy_ptr
对象超出范围,即使其他客户端持有shared_ptr
版本
Once all
lazy_ptr
objects go out of scope, any weak references can no longer be locked, even if other clients are holdingshared_ptr
versions
不能控制不同主题上的对象构建
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.
推荐答案
我会感谢对其他尝试调解这些问题的任何指示,或任何正在进行的工作。 >
要创建不需要参数的延期构造:
To create deferred construction that requires no parameters:
boost :: bind ; T *>(),param1,param2)
将创建一个函数对象,执行 new T(param1,param2)
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.
要创建支持此延迟构造的shared_ptr:
To create a shared_ptr that supports this deferred construction:
使用标准 boost :: shared_ptr
(例如,在您的创建类中)捆绑您的工厂,然后您将记录所描述的结果,包括适当的 weak_ptr
功能...
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();
共享指针将唯一标识为 true
在对象的生命周期。如果你想让尚未构建与销毁区分开,你可以在工厂运行后设置一个bool。
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.
这篇关于共享,弱和惰性指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!