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 ofr
, but holds an unrelated and unmanaged pointerptr
. If thisshared_ptr
is the last of the group to go out of scope, it will call the storeddeleter
for the object originally managed byr
. However, callingget()
on thisshared_ptr
will always return a copy ofptr
. It is the responsibility of the programmer to make sure that thisptr
remains valid as long as thisshared_ptr
exists, such as in the typical use cases whereptr
is a member of the object managed byr
or is an alias (e.g., downcast) ofr.get()
For example:
auto array = std::make_shared<int[]>(10);
auto segment = std::shared_ptr<int>(array, &array[5]);