在函数中返回向量后清除内存 [英] Clear the memory after returning a vector in a function

查看:80
本文介绍了在函数中返回向量后清除内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,可以在其中处理和存储大量数据,然后将结果作为类的向量返回.此函数中存储的数据量非常大,我想在函数完成工作后清除该函数的存储内存.是否有必要这样做(该功能会自动清除内存)还是应该通过某些功能清除内存?

I have a function which processes and stores a lot of data in it and then it returns the results as a vector of class. The amount of data stored in this function is tremendous and I want to clear the storage memory of the function after it finished its job. Is it necessary to do so (does the function automatically clear the memory) or should I clear the memory by some function?

更新:

vector<customers> process(char* const *filename, vector<int> ID)
{
    vector<customers> list_of_customers;
    (perform some actions)
    return list_of_customers;
}

推荐答案

在函数内本地定义的变量将在函数范围的末尾自动释放.任何对象的析构函数也将被调用,这将释放那些对象分配的所有内存(如果对象编码正确).这样的对象的一个​​示例是std::vector.

Variables defined locally within the function will be automatically released at the end of the function scope. The destructors for any objects will also be called, which should free any memory allocated by those objects (if the objects were coded correctly). An example of such an object would be a std::vector.

您为new分配的所有内容都必须具有相应的delete才能释放存储.尝试避免自行分配,而是使用 RAII ,即容器或智能指针.

Anything you've allocated yourself with new must have a corresponding delete to release the storage. Try to avoid doing your own allocation and use RAII instead, i.e. containers or smart pointers.

这篇关于在函数中返回向量后清除内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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