如何正确清除没有指针的列表中的内存?

时间:2013-07-10 08:34:47

标签: c++ visual-c++

我正在学习c ++而不完全确定如何正确插入和删除列表中的某些或所有项目。这就是我在做的事。

结构

struct  _STRUCT_TYPE_
{
    int nReference
    char[128] strAddress
};

定义清单

std::list<_STRUCT_TYPE_> m_ListExample

插入列表

_STRUCT_TYPE_ pStruct;
pStruct.nReference = nVar1;
pStruct.strAddress = strVar2
m_ListExample.push_back(pStruct);

清除列表

m_ListExample.clear();

我做得对吗?可以做得更好吗?我很感兴趣。

1 个答案:

答案 0 :(得分:0)

您的std :: list已分配堆栈,这意味着它将自动清除。

如果你有

int x;

你可以做的不多,因为它是堆栈分配,但是如果你有

int* x = new int;

int* x = malloc(sizeof(int));

你将面临呼叫

delete x;

free(x);

堆栈分配通常更快但如果您真的想要更改代码以便列表是堆分配的,并且您可以确定内存已取消分配,则可以执行以下操作:

struct  _STRUCT_TYPE_
{
    int nReference
    char[128] strAddress
};

std::list<_STRUCT_TYPE_>* m_ListExample;

int main()
{
    _STRUCT_TYPE_ pStruct;
    pStruct.nReference = nVar1;
    pStruct.strAddress = strVar2
    m_ListExample->push_back(pStruct);

    //when done
    m_ListExample->clear();
    delete m_ListExample;

    return 0;
}