Search code examples
c++shared-ptr

Referencing a element of a shared_ptr


Please consider the following code using a raw pointer, where I also reference different parts with another pointer;

float* data = new float[9]; 
float* d = &data[3]; // may be d = &data[6] 

Now, I am want to use shared_ptr for above code, but I am unsure how to use shared_ptr for above case.


Solution

  • There is a constructor that takes a shared pointer and an unrelated raw pointer. That's what you want. This can also point at whatever else you want, as long as it shares the lifetime of the passed-in shared pointer.

    // until C++17
    std::shared_ptr<float[]> data(new float[9]);
    // more efficient but requires C++20
    auto data = std::make_shared<float[]>(9);
    
    std::shared_ptr<float[]> d(data, &data[3]);
    
    assert(&d[0] == &data[3]);