释放存储在向量中的对象? [英] Deallocating objects stored in a vector?

查看:152
本文介绍了释放存储在向量中的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类创建一个对象的向量。在这个类的解构函数中,我试图释放分配给对象的内存。我试图这样做只循环通过向量。所以,如果向量被称为地图我在做:

I have a class that creates a vector of objects. In the deconstructor for this class I'm trying to deallocate the memory assigned to the objects. I'm trying to do this by just looping through the vector. So, if the vector is called maps I'm doing:

Building::~Building() {
    int i;
    for (i=0; i<maps.size(); i++) {
        delete[] &maps[i];
    }
}



当我运行这个程序segfaults时释放内存。我想我所做的是删除存储对象的数组,而不是对象本身。它是否正确?

When I run this the program segfaults while deallocating memory. I think what I'm doing is actually deleting the array storing the objects and not the objects themselves. Is this correct? If not any ideas as to what I'm doing wrong?

推荐答案

这取决于向量是如何定义的。

It depends on how vector is defined.

如果地图是向量< myClass *> ,则删除具有类似以下内容的每个元素:

If maps is a vector<myClass*> you delete each element with something similar to:

for ( i = 0; i < maps.size(); i++)
{
    delete maps[i];
}



如果maps是向量< myClass> code>我不认为你需要删除个别元素。

If maps is a vector<myClass> I don't think you need to delete the individual elements.

这篇关于释放存储在向量中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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