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.
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};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With