Hi All
I have created a smart pointer implementation. Below is the code. Could you guys have a look and suggest that approach is correct or not.
One point I want to mention that, for count I have used static. On net I found that pointer variable is used.
Can u guys please suggest why can’t we used static count?
Below is the code:
Code:
#include<iostream>
using namespace std;
template<class T>
class sharedPtr
{
T* ShrdPtr;
static int refCount;
public:
sharedPtr()
{
ShrdPtr = new T;
refCount++;
cout <<" \nIn Default Ctr: "<<refCount;
}
~sharedPtr( )
{
if( --(refCount) == 0 )
delete ShrdPtr;
std::cout << "inside destructor refCount = " << refCount << "\n";
}
sharedPtr<T>& operator=( const sharedPtr& ptr );
sharedPtr( const sharedPtr& ptr );
// T* operator->( ) { return ShrdPtr; }
// T& operator*() { return *ShrdPtr; }
};
template<class T> sharedPtr<T>& sharedPtr<T>::operator=( const sharedPtr<T>& ptr )
{
this->ShrdPtr = ptr.ShrdPtr;
this->refCount = ptr.refCount;
std::cout << endl<<"inside assignment operator="<<refCount<<endl;
return *this;
}
template<class T>
sharedPtr<T>::sharedPtr( const sharedPtr& ptr )
{
this->ShrdPtr = ptr.ShrdPtr;
refCount++;
this->refCount = ptr.refCount;
std::cout << endl<<"inside copy constructor="<<refCount<<endl;
}
template<class T> int sharedPtr<T>::refCount = 0;
int main( int argc, char* argv[] )
{
{
sharedPtr<int> p ;
sharedPtr<int> q = p;
sharedPtr<int> x(q);
sharedPtr<int> z;
z = q;
}
return 0;
}
Implementation still not complete. Waiting for suggestion before proceeding.
Thanks