C ++释放自定义类向量的正确方法 [英] C++ Correct way to free a vector of a custom class

查看:120
本文介绍了C ++释放自定义类向量的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有自己的自定义课程,例如:

I have my custom class, like:

class MyClass {

   public:
        int i;
        std:string name;

        void DoSomeStuff();

}

和另一个包含我的自定义课程列表的课程:

and another class with a list of my custom class:

class MyClassList {

    public:
        std::vector<MyClasss> myClassList;
}

为了释放内存中所有使用的向量空间,列表析构函数应该如何:

How shall be the list destructor in order to release all used vector space in memory:

MyClassList::~MyClassList 
{
    myClassList.clear();
    delete &myClassList;
}

该代码是正确的,冗余的还是错误的?

Is that code right, redundant or wrong ?

感谢您的帮助...

推荐答案

您无需执行任何操作,只需使其超出范围即可. RAII 将确保清除向量内存当您的MyClassList实例超出范围时.

You don't need to do anything, just let it fall out of scope. RAII will ensure that the vector memory is cleaned up when your instance of MyClassList falls out of scope.

这篇关于C ++释放自定义类向量的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆