开发者

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

开发者 https://www.devze.com 2023-02-20 11:51 出处:网络
If a vector is placed in stack, it will be destructed automatically at the end of its automatic variable scope开发者_如何学C.

If a vector is placed in stack, it will be destructed automatically at the end of its automatic variable scope开发者_如何学C.

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?


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
}


Make sure each B class that you use in the vector, deletes its own allocated space in the destructor, so when the vector goes out of scope, you wont be left with memory leaks

0

精彩评论

暂无评论...
验证码 换一张
取 消