Hello. Here is a sample code:

struct BUFF { int * a; int * b; int * ...; }; main() { BUFF buff; buff.a = new int[32]; buff.b = new int[32]; buff.... = new int[32]; // какие-то действия ... // освобождение памяти delete[] buff.a; delete[] buff.b; delete[] buff.....; } 

Question:

Are there any ways to delete all the structure fields at once and not one line of " delete [] buff. ..."?

  • 2
    It is impossible. How many new , so much and delete . - maestro
  • Designer and destructor ... - Harry

2 answers 2

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(); 

    I do not understand, who prevents to write the designer and the destructor once?

     struct BUFF { int * a; int * b; int * ...; BUFF():a(new int[32]),b(new int[32]),...{} ~BUFF(){ delete[]a; delete[] b; ... } }; main() { BUFF buff; // какие-то действия ... // освобождение памяти - НИЧЕГО } 

    You can show a special tricky ... st :) and do so:

     struct BUFF { int * a; int * b; int * ...; BUFF():a(new int[128]) { b = a + 32; ... } ~BUFF(){ delete[]a; } }; 

    In principle, with a large number of fields and the frequent creation and deletion of BUFF may even be effective due to a sharp decrease in access to the memory manager.