使用后自动释放内存
automatic memory release after use
有很多地方我得到了这样的代码:
some_function_signature()
{
T a;
T b = f1(a);
T c = f2(b);
T d = f3(c);
...
}
如您所见,在这样的函数中,a
被传递给f1()
以产生b
,然后b
传递给f2()
以产生c
,依此类推。这些变量在函数调用后不会使用(f1,f2,f3
...(。它们拥有大量内存(例如T
是大图像数据(。这里的问题是,在这个函数中,累积的内存消耗可能很大,我想减少它。等待 T 的析构函数释放内存会使some_function_signature()
的峰值内存使用量非常大。
我可以做这样的事情来释放使用后的内存:
some_function_signature()
{
T a;
T b = f1(a); a.free();
T c = f2(b); b.free();
T d = f3(c); c.free();
...
}
我想知道我是否可以使这个过程自动化和更优雅。例如,作用域内存管理进程或使用某种引用计数,但我只是不知道如何在这里最好地应用这些方法。
这看起来像是移动语义的一个案例。确保T
和f1/2/3
支持移动语义,并将示例更改为
some_function_signature()
{
T a;
T b = f1(std::move(a));
T c = f2(std::move(b));
T d = f3(std::move(c));
...
}
这将允许T f1(T&& t)
回收移入的图像。
你可以尝试这样的事情:
T d;
{
T c;
{
T b;
{
T a;
b = f1(a);
} //a goes out of scope and is destroyed here
c = f1(b);
} //b goes out of scope and is destroyed here
d = f3(c);
}//c goes out of scope and is destroyed here
相关文章:
- 如何在c++中释放内存
- 为什么这个 std::queue/指向结构的指针列表直到 List.Size() == 0 才释放内存?
- std::unordered_map析构函数不释放内存?
- 在C++中释放内存期间,迭代器与指针有何不同
- 使用共享指针时,从共享指针本身释放内存的机制是什么
- 释放内存(主题模板)时出现问题
- 使用后自动释放内存
- C++ 如何释放内存
- 从函数内对象的向量中释放内存
- C++ 在不释放内存的情况下调用析构函数
- 多个线程之间的获取-释放内存顺序
- C++ - 析构函数只是释放内存还是实际删除对象
- 使用 RAII 替换最终块以释放内存
- 如何通过带有指向基类的指针的删除运算符释放内存
- 代码中的"sprintf"用法是否需要释放内存?
- C++何时使用 delete[] 并正确释放内存?
- 为什么此获取和释放内存围栏不能给出一致的值?
- 抛出新表达式的参数子表达式时释放内存
- 在这种情况下,如何释放内存?
- 在 c++ 中应按什么顺序释放内存?