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]);