Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a shared_ptr to an offset of an array

Let's say I have a shared_ptr to an array:

std::shared_ptr<int> sp(new T[10], [](T *p) { delete[] p; });

And a method:

shared_ptr<T> ptr_at_offset(int offset) {
    // I want to return a shared_ptr to (sp.get() + offset) here
    // in a way that the reference count to sp is incremented...
}

Basically, what I'm trying to do is return a new shared_ptr that increments the reference count, but point to an offset of the original array; I want to avoid having the array deleted while a caller is using the array at some offset. If I just return sp.get() + offset that may happen, right? And I think initializing a new shared_ptr to contain sp.get() + offset doesn't make sense either.

New to C++, so not sure if I'm approaching this correctly.

like image 771
u3l Avatar asked Sep 27 '17 17:09

u3l


1 Answers

You should be able to use the aliasing constructor:

template< class Y > 
shared_ptr( const shared_ptr<Y>& r, element_type* ptr ) noexcept;

This shares the ownership with the given shared_ptr, but makes sure to clean up according to that one, not the pointer you give it.

shared_ptr<T> ptr_at_offset(int offset) {
    return {sp, sp.get() + offset};
}
like image 51
chris Avatar answered Oct 21 '22 09:10

chris