c++boostboost-smart-ptr

Is this the correct way to use the boost::scope_ptr with array?


Since boost::scoped_ptr doesn't work with [] indexing operator, I am trying to do a workaround like this

{
    boost::scoped_ptr<float> data_ptr;
    float *data = new float(SIZE);
    data_ptr.reset(data);
    ...
}

Will the array be freed later on? Is there a better way to do this?


Solution

  • float *data = new float(SIZE);
    

    This line dynamically allocates a single float and initializes it to SIZE, it isn't allocating an array of SIZE elements. The code you've shown has well defined behavior, other than the fact that it's obviously not what you want.

    To dynamically allocate an array use

    float *data = new float[SIZE];
    //                     ^    ^
    // use "new float[SIZE]()" if you want to zero initialize all the elements
    

    However, if you do that your code now has undefined behavior because the scoped_ptr will call delete to destroy the array, but because allocated the memory using new[], you need delete[] to be called instead. The solution is to use boost::scoped_array.

    {
        boost::scoped_array<float> data_ptr(new float[SIZE]);
    
        data_ptr[0] = 0;  // array indexing works too
        ...
    }  // delete[] will be called to destroy the array