Search code examples
c++new-operatordynamic-memory-allocation

Using dynamic memory in the proper scope


I felt that it is a good practice to use new within the same scope delete should be used. It is much easier to keep track of memory. For example, suppose I have:

class Obj;

Obj* create() {
    Obj* object = new Obj();
    // do a bunch of messy work with object
    return object;
}

int main() {
    Obj* o = create();
}

The issue with the code above is that it is not immediately obvious that o needs to be freed. So instead, I would prefer:

int main() {
    Obj* o = new Obj();
    // do a bunch of messy work with o
}

This way, I would remember to delete o. However, this too is causing me issues. I'm working on a larger project at the moment and my main() is beginning to look large and messy due to a bunch of statements that can easily be grouped together within a single function.

So which practice should I use when working on larger projects (or any sized project for that matter) i.e, should I use new within main() to better keep track of memory but pay the price of messier code or should I use new within functions to have cleaner code but have a slightly more difficult time manually managing memory?

My apologies if this question is too specific or not as important as I'm making it out to be.


Solution

  • You're correct that passing around pointers makes it difficult to track ownership. If you have access to C++11, you could return an std::unique_ptr to express the intent of passing ownership to the caller. If you only have access to C++03 features, the boost library features boost::unique_ptr, too.

    Using std::unique_ptr std::shared_ptr, and std::weak_ptr where appropriate would also simplify memory management (prevent mismanagement) when exception handling comes into play.

    Using new and delete expressly has few uses in modern C++ short of writing custom containers, allocators, and other lower-level tasks.

    In short: Use smart pointers when you can, and manual memory management when you have to.