我可以使用块来管理 C++ 中的内存消耗吗?

发布于 2024-07-14 11:26:47 字数 299 浏览 9 评论 0原文

我试图在 C++ 程序中节省一些内存,我想知道是否可以使用块作为变量的范围(如 Perl 中)。 假设我有一个巨大的对象,它执行一些计算并给出结果,这样做是否有意义:

InputType  input;
ResultType result;

{
    // Block of code
    MyHugeObject mho;
    result = mho.superHeavyProcessing();
}

/*
   My other code ...
*/

我可以期望该对象在退出块时被销毁吗?

I'm trying to gain some memory saving in a C++ program and I want to know if I can use blocks as a scope for variables (as in Perl). Let's say I have a huge object that performs some computations and gives a result, does it makes sense to do:

InputType  input;
ResultType result;

{
    // Block of code
    MyHugeObject mho;
    result = mho.superHeavyProcessing();
}

/*
   My other code ...
*/

Can I expect the object to be destroyed when exiting the block?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

空城之時有危險 2024-07-21 11:26:47

是的你可以。

一旦变量超出范围,析构函数就会被调用,并且它应该释放堆分配的内存。

Yes, you can.

The destructor will be called as soon as the variable falls out of scope and it should release the heap-allocated memory.

跨年 2024-07-21 11:26:47

是的,绝对是的,除了节省内存之外,当您希望析构函数在调用析构函数时实际执行某些操作时,通常会使用在作用域退出时调用析构函数(请参阅 RAII)。 例如,创建基于范围的锁并以异常安全的方式轻松释放它,或者确定性地放弃对共享或宝贵资源(如文件句柄/数据库连接)的访问。

-瑞克

Yes absolutely, and in addition to conserving memory, calling the destructor on scope exit is often used where you want the destructor to actually do something when the destructor is called (see RAII). For example, to create a scope based lock and release easily it in an exception safe way, or to let go of access to a shared or precious resource (like a file handle / database connection) deterministically.

-Rick

长伴 2024-07-21 11:26:47

请记住,您使用 new/malloc 在堆上分配的任何在析构函数中释放的内存可能不会被释放回操作系统。 您的进程可能会保留它,并且操作系统在进程终止之前不会取回它。

Just remember that any memory you allocate on the heap using new/malloc that is freed in the destructor probably won't be released back to the OS. Your process may hold onto it and the OS won't get it back until the process terminates.

挖鼻大婶 2024-07-21 11:26:47

是的。 它将在右花括号处被破坏。 但要注意在堆栈上分配非常大的对象。 这可能会导致堆栈溢出。 如果您的对象还分配大量内存,请确保它是使用 new、malloc 或类似方法分配的堆。

Yes. It will be destroyed at the closing curly brace. But beware of allocating very large objects on the stack. This can causes a stack overflow. If you object also allocates large amounts memory, make sure it is heap allocated with new, malloc, or similar.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文