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_ptrwhich shares ownership information with the initial value ofr, but holds an unrelated and unmanaged pointerptr. If thisshared_ptris the last of the group to go out of scope, it will call the storeddeleterfor the object originally managed byr. However, callingget()on thisshared_ptrwill always return a copy ofptr. It is the responsibility of the programmer to make sure that thisptrremains valid as long as thisshared_ptrexists, such as in the typical use cases whereptris a member of the object managed byror 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]);
