I have a struct, which contains a few vectors, defined as follows:
#include <vector>
using namespace std;
struct data{
vector<float> x;
vector<float> y;
vector<float> z;
}
Which I later use as such:
data d;
for(int i; i<3; i++){
d.x.push_back(i)
d.y.push_back(i*2)
d.z.push_back(i*3)
}
And now I want to safely delete data
in a way the completely deallocates all of the memory associated with it. I think that the way to do this is to write a simple destructor which clears and deallocates each field of data
, and then delete
the object:
struct data{
vector<float> x;
vector<float> y;
vector<float> z;
~data(){
vector<tempObject>().swap(x);
vector<tempObject>().swap(y);
vector<tempObject>().swap(z);
}
}
and then this should work:
data d;
for(int i; i<3; i++){
d.x.push_back(i)
d.y.push_back(i*2)
d.z.push_back(i*3)
}
delete data;
where I've made use to the top answer here to deallocate the vectors.
Will this work? If not, can you describe why and/or suggest an alternative? I understand that the memory will be freed once d
leaves scope, but I need to free the memory before that happens.