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.
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’.
is how you would use the stack. Before executing the next statement after this, C++ promises to create a temporary object of type
Demoand call the no-args constructor. After the last statement in the current{}lexical block that referenceslocalDemo, 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:
Then the automatically-generated constructor for
Proletariatwill call theDemoconstructor, and the the destructor will always call theDemodestructor.If you have a constructor with args, you write something like:
to pass those args.