markusneg
markusneg

Reputation: 3

Better shared_ptr by distinct types for "ownership" and "reference"?

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:

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

Upvotes: 0

Views: 160

Answers (1)

nate
nate

Reputation: 1871

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.

Upvotes: 0

Related Questions