Better shared_ptr by distinct types for “ownership” and “reference”?

*爱你&永不变心* 提交于 2021-02-05 10:44:05

问题


I would like to use a pointer-like object

Ownership<Type> m_foo

for the owning object and handle

Reference<Type> m_someFoo

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).

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:

  • 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 unlocking m_lockCount--
  • Ownership can't release object when m_lockCount != 0

This solution would be especially feasible for few Reference instances and high access rates through References.


回答1:


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.



来源:https://stackoverflow.com/questions/38777357/better-shared-ptr-by-distinct-types-for-ownership-and-reference

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