Home > database >  A shared pointer to a section of memory belonging to another shared pointer
A shared pointer to a section of memory belonging to another shared pointer

Time:08-14

I know shared pointers are implied to share the same memory. But what if my shared pointer points to an element which is not the first in the memory of another shared pointer?

Consider a raw pointer example:

int* array = new int[10];
int* segment = &array[5];

Can I make the same thing with array and segment being shared pointers? Will they count references in this case?

CodePudding user response:

std::shared_ptr has an aliasing constructor for exactly this kind of situation:

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

The aliasing constructor: constructs a shared_ptr which shares ownership information with the initial value of r, but holds an unrelated and unmanaged pointer ptr. If this shared_ptr is the last of the group to go out of scope, it will call the stored deleter for the object originally managed by r. However, calling get() on this shared_ptr will always return a copy of ptr. It is the responsibility of the programmer to make sure that this ptr remains valid as long as this shared_ptr exists, such as in the typical use cases where ptr is a member of the object managed by r or is an alias (e.g., downcast) of r.get()

For example:

auto array = std::make_shared<int[]>(10);
auto segment = std::shared_ptr<int>(array, &array[5]);
  • Related