Search code examples
c++c++17shared-ptr

std::shared_ptr with aliasing constructor, is it possible the retrieve the initial pointer value?


This c++17 code uses shared_ptr's (8) aliasing constructor

#include <iostream>
#include <memory>

using namespace std;

int main()
{
  auto shared_1 = std::shared_ptr<int[]>(new int[10], std::default_delete<int[]>());

  int* p_data = shared_1.get(); 

  auto shared_2 = std::shared_ptr<int[]>(shared_1, p_data + 5); // aliasing constructor

  std::cout << std::hex << p_data << "\t" << shared_1.get() << std::endl;

  std::cout << std::hex << p_data + 5 << "\t" << shared_2.get() << std::endl; // Is it possible 
                                                                              // to retrieve the
                                                                              // initial p_data value?
}

and prints:

0x556f38865e70    0x556f38865e70
0x556f38865e84    0x556f38865e84

Question: imagine that I only store shared_2 (and not shared_1 nor the +5 offset), does this p_data initial value (stored in shared_1) is lost or if is it still possible to retrieve it from shared_2 only?


Solution

  • You cannot retrieve p_data from shared_2 alone.

    The value stored in shared_2 need bear no relation to the original pointer, and there is no way to retrieve the "original" value used for the initial shared_ptr with which the aliasing pointers all share the same management block.

    You could use a custom deleter, and store the data in the deleter when you made the shared_ptr, and then use get_deleter to retrieve the deleter, and thus the data from it.