通过“所有权"的不同类型更好的shared_ptr.和“参考"? [英] Better shared_ptr by distinct types for "ownership" and "reference"?
问题描述
我想使用类似指针的对象
I would like to use a pointer-like object
所有权<类型>m_foo
用于拥有对象和句柄
Reference< Type>m_someFoo
作为另一个上下文中的经典指针",而我的 Reference 应该知道何时不再存在原始对象(例如,通过返回nullptr),并且还应该有可能防止原始对象删除(锁定)一小段时间.
as a classical "pointer" in another context, whereas my Reference should know when the original object does not exist anymore (e.g. by returning nullptr) and it should furthermore be possible to prevent the original object from deletion for a small period of time (locking).
我知道 shared_ptr (所有权)和 weak_ptr (参考)提供了相似的功能.但是,锁定 weak_ptr 并访问原始ptr涉及到创建 shared_ptr 的过程,该过程相当缓慢.同样,我无法决定在访问原始ptr之前不锁定 weak_ptr (例如,在知道该对象当前未删除的情况下).
I know that shared_ptr (Ownership) and weak_ptr (Reference) provide similar functionality. However, locking a weak_ptr and accessing the raw ptr involves creation of a shared_ptr which is rather slow. Also I cannot decide not to lock the weak_ptr before accessing the raw ptr (e.g. while knowing that the object is not being deleted right now).
按以下方式实现所有权和参考是否明智:
Is it wise to implement Ownership and Reference as follows:
- 所有权知道其引用的地址(例如
std :: list< Reference< Type> *> *>
) - 当拥有的对象衰减时,这些 Reference 设置为nullptr
- 参考包含对所有权 中的
- 在锁定
m_lockCount ++
后,在锁定 - 所有权无法释放对象
uint m_lockCount
的ptr m_lockCount ++
时当 m_lockCount!= 0
时,- Ownership knows addresses of its References (e.g.
std::list<Reference<Type>*>
) - When the owned object decays, these References are set to nullptr
- Reference contains ptr to an
uint m_lockCount
in Ownership - upon locking,
m_lockCount++
, upon unlockingm_lockCount--
- Ownership can't release object when
m_lockCount != 0
对于少数 Reference 实例和通过 Reference s的高访问率,此解决方案特别可行.
This solution would be especially feasible for few Reference instances and high access rates through References.
推荐答案
您提出的替代方案比 shared_ptr/weak_ptr
慢得多,这仅仅是因为使用了 std :: list的想法
指向引用的后向指针.如果仅在单线程模式下工作,那只会增加额外的开销.加上线程,您需要一个锁来原子地操作您的引用计数和引用列表(尽管一旦有了列表,就不需要计数). shared_ptr \ weak_ptr
给您的对象增加了两个指针开销,并且没有超出初始指针的动态分配.
Your proposed alternative would be much slower than shared_ptr/weak_ptr
simply due to the idea of using a std::list
for back pointers to the references. If you only work in single threaded mode that would the only addition overhead. Add in threading and you need a lock to manipulate your reference count and reference list atomically (though once you have a list, you don't need the count). shared_ptr\weak_ptr
adds a couple of pointers overhead to your object, and has no dynamic allocations past the initial one.
这篇关于通过“所有权"的不同类型更好的shared_ptr.和“参考"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!