Skip to content

Latest commit

 

History

History
82 lines (45 loc) · 3.55 KB

memory-management-examples.md

File metadata and controls

82 lines (45 loc) · 3.55 KB
description title ms.date helpviewer_keywords ms.assetid
Learn more about: Memory Management: Examples
Memory Management: Examples
11/04/2016
objects [MFC], memory allocation
data structures [MFC]
arrays [MFC], allocating resources
objects [MFC], allocating memory
data structures [MFC], allocating memory
examples [MFC], memory allocation
heap allocation [MFC], examples
memory allocation [MFC], arrays
MFC, memory management
struct memory allocation [MFC]
types [MFC], memory allocation
memory allocation [MFC], objects
memory allocation [MFC], examples
arrays [MFC], memory management
frame allocation [MFC]
memory allocation [MFC], data structures
f10240f8-b698-4c83-9288-97a54318930b

Memory Management: Examples

This article describes how MFC performs frame allocations and heap allocations for each of the three typical kinds of memory allocations:

Allocation of an Array of Bytes

To allocate an array of bytes on the frame

  1. Define the array as shown by the following code. The array is automatically deleted and its memory reclaimed when the array variable exits its scope.

    [!code-cppNVC_MFC_Utilities#1]

To allocate an array of bytes (or any primitive data type) on the heap

  1. Use the new operator with the array syntax shown in this example:

    [!code-cppNVC_MFC_Utilities#2]

To deallocate the arrays from the heap

  1. Use the delete operator as follows:

    [!code-cppNVC_MFC_Utilities#3]

Allocation of a Data Structure

To allocate a data structure on the frame

  1. Define the structure variable as follows:

    [!code-cppNVC_MFC_Utilities#4]

    The memory occupied by the structure is reclaimed when it exits its scope.

To allocate data structures on the heap

  1. Use new to allocate data structures on the heap and delete to deallocate them, as shown by the following examples:

    [!code-cppNVC_MFC_Utilities#5]

Allocation of an Object

To allocate an object on the frame

  1. Declare the object as follows:

    [!code-cppNVC_MFC_Utilities#6]

    The destructor for the object is automatically invoked when the object exits its scope.

To allocate an object on the heap

  1. Use the new operator, which returns a pointer to the object, to allocate objects on the heap. Use the delete operator to delete them.

    The following heap and frame examples assume that the CPerson constructor takes no arguments.

    [!code-cppNVC_MFC_Utilities#7]

    If the argument for the CPerson constructor is a pointer to char, the statement for frame allocation is:

    [!code-cppNVC_MFC_Utilities#8]

    The statement for heap allocation is:

    [!code-cppNVC_MFC_Utilities#9]

See also

Memory Management: Heap Allocation