DrHouse
DrHouse

Reputation: 99

C++ Memory Management diffrences with Heap Allocation and Frame Allocation

I am slightly confused about how memory management works in C++, I understand when you use pointers (new/delete) but I'm lost when it comes to Frame allocation.

Say I have a simple class (Using QT Classes)

class Demo {
    public:
        Demo();
        ~Demo();
        QString AString() const;
        void setAString(const QString &value);
    private:
        QString aString;
};

And I Allocate it using a pointer

Demo *testInst = new Demo();

Now I understand when i call "delete testInst;" That is freed, but I'm confused about the out of scope part on Frame Allocations. Does that mean when I call delete, all those in the class that are not pointers are automatically freed, or do i have to do specific memory management within the deconstructor of the Demo class? Or does it mean if I leave the class those variables are freed?

I'm new to C++ and came from a .NET background so I'm not 100% understanding of manual memory management.

Upvotes: 1

Views: 406

Answers (2)

bmargulies
bmargulies

Reputation: 100013

There are two allocation disciplines in C++. Heap and Stack. I'm suspecting that you mean Stack when you write 'frame'. Sometimes, especially in old C sources, it's called 'auto'.

Demo localDemo;

is how you would use the stack. Before executing the next statement after this, C++ promises to create a temporary object of type Demo and call the no-args constructor. After the last statement in the current {} lexical block that references localDemo, C++ promises to call the destructor and release the storage. The storage is, in fact, part of the stack frame of the procedure or block.

A related question is a data member of class type. If you write:

class Proletariat {
   private:
      Demo localDemo;
};

Then the automatically-generated constructor for Proletariat will call the Demo constructor, and the the destructor will always call the Demo destructor.

If you have a constructor with args, you write something like:

class Proletariat {
   private:
      Demo localDemo;
   public:
      Proletariat() : localDemo("omeD") {}
}

to pass those args.

};

Upvotes: 1

Chris
Chris

Reputation: 17535

In plain C++ you are generally going to need a delete for every new (oversimplification, I know) that is in your code.

In the example above you need to do no further memory management other than calling delete as have already shown. If your class had member variables that were allocated on the heap (for example, aString was a QString* that you had new'd in your constructor, then in your destructor you would also need to delete it.

Upvotes: 0

Related Questions