I have the following code that ends up calling the destructor twice on an object and crashing. What is the best practice way of implementing this design to avoid such issues?
class DataStore {
private:
uint8_t* data;
int dataLength;
public:
DataStore(int length){
data = new uint8_t[length];
dataLength = length;
}
~DataStore(){
printf("DataStore Destructor\n");
delete [] data;
}
};
class DataStoreHelper {
private:
DataStore _dataStore;
public:
DataStoreHelper(DataStore& dataStore) : _dataStore(dataStore){
}
};
int main(int argc, char** argv) {
DataStore dataStore(10);
DataStoreHelper dataStoreHelper(dataStore);
}
With the following output:
DataStore Destructor
DataStore Destructor
free(): double free detected in tcache 2
I could fix the problem by storing _dataStore as a pointer, but I really want to know is this the best practice method of implementation or is there a better way?