This article describes how MFC performs frame allocations and heap allocations for each of the three typical kinds of memory allocations:
To allocate an array of bytes on the frame
{
const int BUFF_SIZE = 128;
// Allocate on the frame
char myCharArray[BUFF_SIZE];
int myIntArray[BUFF_SIZE];
// Reclaimed when exiting scope
}
To allocate an array of bytes (or any primitive data type) on the heap
const int BUFF_SIZE = 128;
// Allocate on the heap
char* myCharArray = new char[BUFF_SIZE];
int* myIntArray = new int[BUFF_SIZE];
To deallocate the arrays from the heap
delete [] myCharArray;
delete [] myIntArray;
To allocate a data structure on the frame
struct MyStructType { int topScore;};
void SomeFunc(void)
{
// Frame allocation
MyStructType myStruct;
// Use the struct
myStruct.topScore = 297;
// Reclaimed when exiting scope
}
The memory occupied by the structure is reclaimed when it exits its scope.
To allocate data structures on the heap
// Heap allocation
MyStructType* myStruct = new MyStructType;
// Use the struct through the pointer ...
myStruct->topScore = 297;
delete myStruct;
To allocate an object on the frame
{
CPerson myPerson; // Automatic constructor call here
myPerson.SomeMemberFunction(); // Use the object
}
The destructor for the object is automatically invoked when the object exits its scope.
To allocate an object on the heap
The following heap and frame examples assume that the CPerson
constructor takes no arguments.
// Automatic constructor call here
CPerson* myPerson = new CPerson;
myPerson->SomeMemberFunction(); // Use the object
delete myPerson; // Destructor invoked during delete
If the argument for the CPerson
constructor is a pointer to char, the statement for frame allocation is:
CPerson myPerson( "Joe Smith" );
The statement for heap allocation is:
CPerson* MyPerson = new CPerson( "Joe Smith" );