How to release std::vector if there is no heap memory

前端 未结 3 816
不知归路
不知归路 2021-01-18 05:13

I have a class member variable like this:

vector >  m_stacks;

When I populate it, I do like this:

v         


        
相关标签:
3条回答
  • 2021-01-18 06:02

    You don't have to do anything for m_stacks (a class data member). Acquired memory will be released automatically when the class destructor will be called. This is the purpose for which std::vector is used.

    0 讨论(0)
  • 2021-01-18 06:16

    The destructor for a vector will do two things: it will destroy each element of the vector, then it will free the memory used for the vector itself. This is automatic.

    In your case you have vectors nested two deep, but it doesn't matter. When the top level vector is destroyed it will call the destructor for each vector it contains, and all of those vectors will clean themselves up properly.

    0 讨论(0)
  • 2021-01-18 06:18

    The std::vector destructor calls a delete on the memory it allocates, thereby calling that types (in this instance, a std::vector<int>'s) destructor.

    These data structures all rely on SBRM (Scope bound resource management), or RAII (Resource acquisition is initialisation) principles, in that all memory they allocate is de-allocated once they go out of scope (such as the scope of a class).

    You do not need to worry about the releasing of memory from a std::vector unless it holds a type which points to memory; but does not release it inherently (such as a pointer!).

    0 讨论(0)
提交回复
热议问题