Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ local scopes to reduce memory? [closed]

Tags:

c++

When trying to reduce memory use as much as possible, I have seen some programs use additional local scopes. Is this the best way to reduce footprint? Will the variables be removed from the stack when the brackets close? Would it be better to explicitly delete the objects, or is this equally good? Or would the compiler simply remove extraneous brackets?

void foo()
{
    {
        int a = 4;
        BigObject obj1;
        obj1.operations(a);
    }
    {
        double b = 9;
        BigObject obj2;
        obj2.operations(b);
    }
}
like image 778
dhganey Avatar asked Sep 30 '22 14:09

dhganey


1 Answers

Yes, they introduce new scopes. Objects with automatic storage duration, i.e. objects on the stack ("local variables"), will go out of scope at the end of this scope.

You are guaranteed that destructors are called, but you are not guaranteed that the object is actually removed from the stack (since stack is an implementation detail -- the standard only talks about automatic storage duration).

However, there is rarely a performance reason for doing so. Instead, it can be useful when using the RAII pattern.

Note, however, that this only applies to local variables. Dynamically allocated memory, i.e. objects on the heap (that you allocate with new), will not be released until you explicitly delete them.

Dynamically allocated memory will have to be pointed to by pointers. C++ clearly separates the concepts of pointer to BigObject and BigObject. In other words, your program is ill-formed. You should write:

BigObject* obj1 = new BigObject();
//       ^-- Important!

You can not delete variables with automatic storage, so that part of your question does not make sense.

Not that instead of using new, you should generally prefer using std::unique_ptr instead:

std::unique_ptr<BigObject> obj1 = make_unique<BigObject>();

The memory allocated for your BigObject will be automatically released when obj1 goes out of scope -- this is the RAII pattern.

like image 134
Lstor Avatar answered Oct 22 '22 15:10

Lstor