Tuesday, January 15, 2013

C++ programming: delete memory with reference to pointer

If we delete a memory inside a function, we would also want to update the pointer to NULL so that the caller knows the pointer will not refer to a valid located memory any more. E.g.

   if (p)

   assert(NULL == p);

Therefore, we can use the reference to pointer as the parameter of function delete_memory().

   #include <iostream>

   using namespace std;

   template <typename T>
   void delete_memory(T*& p)
      if (p) {
         delete p;
         p = NULL;

   int main()
      int *p = new int(10);

      cout << "p: " << p << endl;


      cout << "After delete_memory(), p: " << p << endl; // p is 0 now

      return 0;

In the above example, we use template for the delete_memory function so it can handle different types of pointers.

No comments:

Get This <