Thread: matrix destructor

  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    242

    matrix destructor

    My destructor works, but I wanted to check to see if it's correct to do it this way. Here's the code first for the default constructor:
    Code:
    template<typename T, int n>
    Matrix<T, n>::Matrix()
    {
    	T** arr = new T*[n];
    	for (int i = 0; i < n; ++i)
    	{
    		arr[i] = new T[n];
    	}
    	for (int i = 0; i < n; ++i) // rows
    	{
    		for (int j = 0; j < n; ++j) // columns
    		{
    			arr[i][j] = 0;	// T must define 0 and 1
    		}
    	}
    	content = arr;
    }
    Now the destructor:
    Code:
    // destructor
    template<typename T, int n>
    Matrix<T, n>::~Matrix()
    {
    	// free memory on each row
    	for (int i = 0; i < n; ++i)
    	{
    		delete [] content[i];
    		content[i] = NULL;
    	}
    	// delete content entirely
    	delete [] content;
    	content = NULL;
    }
    correct? it at least seems to me that just delete [] content wouldn't set the individual blocks pointed to back as available memory.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Yes, that's correct.

    Assigning pointers to NULL in this context isn't necessary.

    But it's a useful habit that could easily save weeks of confusion if you're re-using pointers and make the mistake of trying to use it after it has been freed.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    May 2009
    Posts
    242
    ok, cool, tx!

  4. #4
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    I think your constructor should have a try-catch block to delete any memory you've allocated, just in case you get a std::bad_alloc exception in one of your calls to new.
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C - access violation
    By uber in forum C Programming
    Replies: 2
    Last Post: 07-08-2009, 01:30 PM
  2. Matrix Help
    By HelpmeMark in forum C++ Programming
    Replies: 27
    Last Post: 03-06-2008, 05:57 PM
  3. Gauss-Jordan Matrix Inversion in C++
    By Max_Power82 in forum C++ Programming
    Replies: 3
    Last Post: 12-03-2006, 08:31 PM
  4. Matrix and vector operations on computers
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 11
    Last Post: 05-11-2004, 06:36 AM