• C++ Programming for Financial Engineering
    Highly recommended by thousands of MFE students. Covers essential C++ topics with applications to financial engineering. Learn more Join!
    Python for Finance with Intro to Data Science
    Gain practical understanding of Python to read, understand, and write professional Python code for your first day on the job. Learn more Join!
    An Intuition-Based Options Primer for FE
    Ideal for entry level positions interviews and graduate studies, specializing in options trading arbitrage and options valuation models. Learn more Join!

C++ pointer

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

C++:
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
C++:
if(!DataPtr)  {.... }                //if DataPtr is NULL
 
Back
Top