c++ - Releasing memory of a struct containing multiple vectors -


having struct such as:

struct pair {     vector<double> a;     vector<double> b; }; 

is using function following proper way release memory after defining , populating such struct? if not, how deal situation?

void release(pair& p){    vector<double>().swap(p.a);    vector<double>().swap(p.b); } 

isn't there way call predefined/std function on pair release memory?

note i'm not using new, etc. definitions pair p;. also, struct more complex pair of vectors have been defined using std::pair.

all related questions in on releasing memory vectors either vectors or vectors of struct, not struct containing multiple vectors. i'm looking elegant way release memory used such struct.

context

the vectors big, , want release memory can. lifetime/usability reaches in middle of function! don't want spread functionality in function multiple functions. these pretty complicated computations , don't want mess things up.

given function not release memory on stack actually. approximately equivalent

p.a.clear();  p.a.shrink_to_fit(); 

the vector remains in memory (just 0 elements).

remember, memory allocated on stack (~ without use of new) gets released when variable occupying memory goes out of scope, not earlier.

so if have variable on stack , want delete it, can limit scope:

struct pair {     vector<double> a;     vector<double> b; };  int main() {   // stuff before...   {      pair p;      // stuff p object...   } // here p gets deleted (all memory gets released)   // stuff after... } 

you mentioned new pair. pointers this:

int main() {    // stuff before...    pair* p = new pair;    // stuff p object...    delete p; // here p gets deleted (all memory gets released)    // stuff after... } 

or commentators requested:

int main() {    // stuff before...    {      auto p = std::make_unique<pair>();      // stuff p...    } // here p gets deleted (all memory gets released)    // stuff after... } 

is wanted achieve?


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -