Set shared_ptr with new_pointer that is old_pointer + offset

Yes this is possible. You can use constructor 8, the aliasing constructor from this reference: https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr

// make sure you use an array deleter
std::shared_ptr<char> osp(new char[1024], std::default_delete<char[]>());

// load the data into your buffer at osp.get()

// Find the offset in the data by parsing
auto const offset = parse_buffer_for_offset(osp.get());

// Now set a new offset into the data
std::shared_ptr<char> nsp(osp, osp.get() + offset);

Now nsp.get() returns the offset address but the original array will get deleted properly.

Note: The offset is a property of each shared_ptr so if you copy the shared_ptr nsp you get another shared_ptr with the same offset. This works whether you construct a new copy or assign a copy to an existing shared_ptr.

This means you can have different shared_ptr with different offsets that all manage the same, underlying resource which will only be cleaned up after all shared_ptr are destroyed.

To see this in operation consider the following code:

std::shared_ptr<char> original_sp(new char[1024], std::default_delete<char[]>());

std::shared_ptr<char> offset_100_sp1(original_sp, original_sp.get() + 100);
std::shared_ptr<char> offset_100_sp2 = offset_100_sp1;

std::shared_ptr<char> offset_200_sp1(original_sp, original_sp.get() + 200);
std::shared_ptr<char> offset_200_sp2 = offset_200_sp1;

std::cout << "\nPointers managing the array: " << original_sp.use_count() << '\n';

std::cout << "\nOffset 100 pointers:" << '\n';
std::cout << std::distance(original_sp.get(), offset_100_sp1.get()) << '\n';
std::cout << std::distance(original_sp.get(), offset_100_sp2.get()) << '\n';

std::cout << "\nOffset 200 pointers:" << '\n';
std::cout << std::distance(original_sp.get(), offset_200_sp1.get()) << '\n';
std::cout << std::distance(original_sp.get(), offset_200_sp2.get()) << '\n';

Output:

Pointers managing the array: 5

Offset 100 pointers:
100
100

Offset 200 pointers:
200
200

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)