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?
A memory block is a group of one or more contiguous chars ("bytes" - see note) of (real or virtual) memory. The malloc(size_t size) function allocates a memory block. The size is how large (in chars) the block should be.
The C programming language provides several functions for memory allocation and management. These functions can be found in the <stdlib. h> header file.
Memory can be allocated dynamically with the malloc() function, and it can be released using free() when it's no longer needed. If the malloc() cannot get the space requested, it returns a NULL.
The delete operator in C++ is used for the deallocation of memory. When we no longer need to use the variable, that means when the memory is no longer required, we have to deallocate or release the memory using the delete operator.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With