Reputation: 1218
I have a piece of code which passes around buffers of data. I want to manage the lifetime of these buffers and so that the memory will not be freed before I am done using it. I realize that std::shared_ptr
is suitable for this task. One thing I want to do is to pass a portion of a buffer to a function while still maintaining the ownership information of the entire buffer (e.g. cut off a header and pass the body to another function).
I noticed that std::shared_ptr
has the following constructor:
template< class Y >
shared_ptr( const shared_ptr<Y>& r, T *ptr );
This constructor allows me to create a new shared_ptr
that shares ownership with r
but stores the pointer ptr
. This is great, but this will cause an increase in the reference count. In some cases, I may wish to pass a portion of a buffer without retaining a shared_ptr
to it. In such a case, I wouldn't need an increase in the reference count. It seems like I would need the following constructor:
template< class Y >
shared_ptr( shared_ptr<Y>&& r, T *ptr );
Note that r
is an rvalue reference. It doesn't appear that such a constructor exists for std::shared_ptr
. Is there a reason for this? Is there a way to do what I want without increasing the reference count?
Upvotes: 3
Views: 161
Reputation: 299870
It may not exist, however there is little reason that should worry you.
Certainly the reference count is incremented when copying a shared pointer, but on the other hand it is decremented when destroying one; and thus:
std::shared_ptr<T> some_pointer = /**/;
std::shared_ptr<R> another_pointer(some_pointer, some_pointer->field());
some_pointer.reset();
Will be semantically identical to a move, and just generate a couple more instructions (if not optimized out).
Upvotes: 1