This documentation is archived and is not being maintained.

CAutoPtr Class

This class represents a smart pointer object.

   typename T
class CAutoPtr


The pointer type.


This class provides methods for creating and managing a smart pointer, which will help protect against memory leaks by automatically freeing resources when it falls out of scope.

Further, CAutoPtr's copy constructor and assignment operator transfer ownership of the pointer, copying the source pointer to the destination pointer and setting the source pointer to NULL. It is therefore impossible to have two CAutoPtr objects each storing the same pointer, and this reduces the possibility of deleting the same pointer twice.

CAutoPtr also simplifies the creation of collections of pointers. Instead of deriving a collection class and overriding the destructor, it's simpler to make a collection of CAutoPtr objects. When the collection is deleted, the CAutoPtr objects will go out of scope and automatically delete themselves.

CHeapPtr and variants work in the same way as CAutoPtr, except that they allocate and free memory using different heap functions instead of the C++ new and delete operators. CAutoVectorPtr is similar to CAutoPtr, the only difference being that it uses vector new[] and vector delete[] to allocate and free memory.

See also CAutoPtrArray and CAutoPtrList when arrays or lists of smart pointers are required.


Header: atlbase.h


// CAutoPtr

#include "stdafx.h"
#include "atlbase.h"

// A simple class for demonstration purposes

class MyClass {
   int iA;
   int iB;
   MyClass(int a, int b);
   void Test();

MyClass::MyClass(int a, int b)
   iA = a;
   iB = b;

void MyClass::Test()
   ATLASSERT(iA == iB);

// A simple function

void MyFunction(MyClass * c)

int main()

   // Create an object of MyClass

   MyClass *pMyC = NULL;
   pMyC = new MyClass(1, 1);

   // Demonstrate Attach by creating a CAutoPtr object
   // and letting it take over the pMyC pointer.
   CAutoPtr <MyClass> apMyC;

   // Call a MyClass method using the -> operator

   // Assign a second CAutoPtr, using the = operator
   CAutoPtr <MyClass> apMyC2;
   apMyC2 = apMyC;

   // Demonstrate the casting operator

   // Demonstrate Detach

   // Demonstrate the pointers automatically
   // freeing the memory allocated by "new"...

return 0;

// That was it. The deletion is automatic: as the class
// goes out of scope the destructors cleans up.

For another example, see the ISAPIFilter Sample.

See Also

Class Members | CHeapPtr | CAutoVectorPtr | ATL Class Overview