Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 239
tunnuz Avatar asked Feb 24 '09 09:02

tunnuz


People also ask

What is a memory block in C?

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.

Does C have memory management?

The C programming language provides several functions for memory allocation and management. These functions can be found in the <stdlib. h> header file.

How can you save memory allocation?

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.

Which is used to solve the memory management problem in C ++?

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.


2 Answers

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.

like image 51
mmx Avatar answered Sep 26 '22 00:09

mmx


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

like image 26
Rick Avatar answered Sep 23 '22 00:09

Rick