Search code examples
c++arraysmemorystlshared-ptr

How to increment shared_ptr in C++?


I get shared_ptr from the function. Shared ptr points to a big array of bytes. I want to return this shared_ptr but point it to the 16th byte in this array. Example with raw pointers (working):

uint8_t* SomeFunction() {
  uint8_t* array = SomeOtherFunction();
  return array + 16;
}

Example with shared pointers (doesn't working):

std::shared_ptr<uint8_t[]> SomeFunction() {
  std::shared_ptr<uint8_t[]> array = SomeOtherFunction();
  return array + 16;
}

I don't want to reallocate the array because it's big and reallocation needs time. I want to return the same shared ptr, but that its get() method would return the raw pointer + 16. But deallocation memory at the original pointer address.

Can I do it? How?


Solution

  • Aliasing constructor might be used:

    std::shared_ptr<uint8_t[]> SomeFunction() {
      std::shared_ptr<uint8_t[]> array = SomeOtherFunction();
      return {array, array.get() + 16};
    }