Background:
While reading about the smart pointers I came across the following sample implementation for Smart Pointer in C++
template < typename T > class SP
{
private:
T* pData; // Generic pointer to be stored
public:
SP(T* pValue) : pData(pValue)
{
}
~SP()
{
delete pData;
}
T& operator* ()
{
return *pData;
}
T* operator-> ()
{
return pData;
}
};
class Person
{
int age;
char* pName;
public:
Person(): pName(0),age(0)
{
}
Person(char* pName, int age): pName(pName), age(age)
{
}
~Person()
{
}
void Display()
{
printf("Name = %s Age = %d \n", pName, age);
}
void Shout()
{
printf("Ooooooooooooooooo",);
}
};
void main()
{
SP<Person> p(new Person("Scott", 25));
p->Display();
// Dont need to delete Person pointer..
}
Questions:
-
This smart pointer gives the benefit that it deletes the Person class object once it goes out of scope. But then do we need to specifically add the code “delete p;” in the main function so that smart pointer class do not leak itself?
-
Since the Person class also has the destructor function, do we really need to call the delete on person’s object? The destructor would be automatically called when Person object goes out ofscope
[1] You do not need to delete
pas you allocate it on the stack. If you did:then you would have to delete it.
[2] You do not need to call
deleteon thePersonobject. That is done by the smart pointer – it is its purpose after all.So your code does not have any memory leaks at its current state.
The smart pointer implementation, however, lacks a copy constructor, assignment operator, etc. so they should be added to avoid some future undesired behaviour.