C++ pointer

  • Thread starter Thread starter Hanks
  • Start date Start date
Joined
7/31/12
Messages
3
Points
11
I am reading C++ design pattern and derivative pricing. Some code is like this

Code:
Wrapper& operator=(const Wrapper<T>& original)
{
      if(this != &original)
          {
             if(DataPtr != 0)
             delete DataPtr;
             DataPtr = (original.DataPtr != 0)? original.DataPtr->clone() : 0;
           }
return *this;
}
(DataPtr is a pointer data number of that class)
Why we have to check the following code and delete DataPtr first before assign it to new address?
if(DataPtr != 0) delete DataPtr;
 
if DataPtr points to a dynamically allocated object this is your last chance to destroy that object and free memory
 
if DataPtr points to a dynamically allocated object this is your last chance to destroy that object and free memory
Thanks. At first I thought it just delete the pointer, the pointed object will not be deleted. Now know that is wrong.
 
In some cases (e.g Singleton pattern) the assignment = is private as well as copy constructor.

DataPtr = (original.DataPtr != 0)? original.DataPtr->clone() : 0;

Q: Since original is a refernce why do we have to check if its data pointer is null?
 
who said pointers are easy ???
10 lines of source code that deserve more than 10 hours studying them
I wonder how many people in this forum do really understand the previous posts? //DD.Poler.MJ
I have been working with pointers for years and still keep learning and discovering new things, I still can not say pointers are easy ;) but yes they are amazing

line number 5 I rather use
Code:
if(!DataPtr)  {.... }                //if DataPtr is NULL
 
Back
Top Bottom