Set shared_ptr with new_pointer that is old_pointer + offset

  • A+

Here is a smart pointer: std::shared_ptr<char> p(new char[size]) which represents array filled with raw binary file content. After (and only after) the whole array is copied from file to RAM, I can parse it, and during this I retrieve some header information (a few first dwords). Then actual data follows.

Without giving much more context, it's handy for me to to set mentioned shared pointer to new address that is beginning of actual data. This address is still in alocated memory. But how to set without losing it?

A question is (yes/no): Is it possible to set p to offset of prevous pointer, without invoking deletion of data?


Yes this is possible. You can use constructor 8, the aliasing constructor from this reference:

// 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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: