I have simple wrapper class around C-style array. I don't want to use std::vector since I want to have only one array even if I do copy of the struct. With std::vector the vector is also copied.
struct RawDataArray {
double* data;
size_t size;
static RawDataArray CreateNew(size_t size){
return RawDataArray(new double[size], size);
}
static RawDataArray CreateNew(size_t size, double defaultValue){
RawDataArray rd = RawDataArray::CreateNew(size);
std::fill_n(rd.data, size, defaultValue);
return rd;
}
static RawDataArray CreateCopy(double* data, size_t size) {
RawDataArray rd = RawDataArray::CreateNew(size);
std::copy(data, data + size, rd.data);
return rd;
}
RawDataArray(double* data, int size) :
data(data),
size(size)
{}
RawDataArray(const RawDataArray& other) :
data(other.data),
size(other.size)
{}
RawDataArray(RawDataArray&& other) noexcept :
data(std::exchange(other.data, nullptr)),
size(std::exchange(other.size, 0))
{}
RawDataArray& operator=(const RawDataArray& other){
return *this = RawDataArray(other);
}
RawDataArray& operator=(RawDataArray&& other) noexcept {
std::swap(data, other.data);
std::swap(size, other.size);
return *this;
}
}
However, the problem is memory management. If I shuffle the wrapper class around, I don't know if I can safely release data.
I was thinking of using std::shared_ptr<double[]>, which is available since C++17 for arrays. Is there any other way or idiom to use?
shared_ptr<vector<double>>
? You could also wrap the vector in some other class and use ashared_ptr<MyWrapper>
.std::vector
, it is copied with each copy of the wrapper object. So I was thinking of C++17shared_ptr
for the raw array. However, I am not sure if there is some "better" way