For these purposes, use the smart pointer std::unique_ptr . When the structure object ceases to exist, destructors for its pointer fields will be automatically called.
In the process, you can assign new values to pointers using the member function of the reset class.
For example,
#include <memory> //... struct BUFF { std::unique_ptr<int[], std::default_delete<int[]>> a; std::unique_ptr<int[], std::default_delete<int[]>> b; std::unique_ptr<int[], std::default_delete<int[]>> c; }; BUFF buff = BUFF(); // ... buff.a.reset(new int[32]); buff.b.reset(new int[32]); buff.c.reset(new int[32]);
Another approach is to write a separate member function of the structure as follows.
#include <algorithm> #include <memory> //... struct BUFF { int *a; int *b; int *c; void reset() { std::initializer_list<int *> l = { a, b, c }; std::for_each(l.begin(), l.end(), std::default_delete<int[]>()); } }; //... BUFF buff = BUFF(); //... buff.reset();
new, so much anddelete. - maestro