0

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?

4

1 回答 1

1
float *data = new float(SIZE);

此行动态分配一个float并将其初始化为,它没有分配元素SIZE数组。SIZE您显示的代码具有明确定义的行为,除了它显然不是您想要的事实。

动态分配数组使用

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

但是,如果您这样做,您的代码现在具有未定义的行为,因为scoped_ptr将调用delete销毁数组,但是由于使用分配了内存new[],因此需要delete[]调用您。解决方案是使用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
于 2015-03-04T15:28:10.880 回答