Search code examples
c++memory-managementvectorraii

Should I clean up ivar C++ vector...?


If a vector is placed in stack, it will be destructed automatically at the end of its automatic variable scope.

What if I have placed a vector in a class?

class A
{
    vector<B> bs;  // B is POD struct.
};

Should I clean it up manually? If so, how should I do?


Solution

  • That vector bs will be destructed when the enclosing class's destructor (i.e A's destructor) will be called.

    void f()
    {
        {
              A a;
              //working with a;
    
        }//<--- here a goes out of scope, so it's destructor is called; 
                //so not only a is destructed but also a.bs
    }