Implementation of a Custom String Manager (Basic Method)


The new home for Visual Studio documentation is Visual Studio 2017 Documentation on

The latest version of this topic can be found at Implementation of a Custom String Manager (Basic Method).

The easiest way to customize the memory allocation scheme for string data is to use the ATL-provided CAtlStringMgr class but provide your own memory allocation routines. The constructor for CAtlStringMgr takes a single parameter: a pointer to an IAtlMemMgr object. IAtlMemMgr is an abstract base class that provides a generic interface to a heap. Using the IAtlMemMgr interface, the CAtlStringMgr allocates, reallocates, and frees the memory used to store string data. You can either implement the IAtlMemMgr interface yourself, or use one of the five ATL-provided memory manager classes. The ATL-provided memory managers simply wrap existing memory allocation facilities:

For the purpose of string memory management, the most useful class is CWin32Heap because it allows you to create multiple independent heaps. For example, if you wanted to use a separate heap just for strings, you could do the following:

// Declare a thread-safe, growable, private heap with initial size 0:
CWin32Heap g_stringHeap(0, 0, 0);

// Declare a string manager that uses the private heap:
CAtlStringMgr g_stringMgr(&g_stringHeap); 

To use this private string manager to manage memory for a CString variable, pass a pointer to the manager as a parameter to the CString variable's constructor:

void PrintPowers(int nBase)
   int n = 1;
   for(int nPower = 0; nPower < 10; nPower++)
      // Use the private string manager, instead of the default:
      CString strPower(&g_stringMgr);

      strPower.Format(_T("%d"), n);
      _tprintf_s(_T("%s\n"), strPower);
      n *= nBase;

Memory Management with CStringT