Can I use blocks to manage memory consumtion in C++?

后端 未结 4 1033
萌比男神i
萌比男神i 2020-12-11 07:10

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

相关标签:
4条回答
  • 2020-12-11 07:27

    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.

    0 讨论(0)
  • 2020-12-11 07:43

    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.

    0 讨论(0)
  • 2020-12-11 07:43

    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.

    0 讨论(0)
  • 2020-12-11 07:46

    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

    0 讨论(0)
提交回复
热议问题