First, the swap method should not be implemented in terms of assignment operator.
I suppose, all it takes to swap two SmartPtr's is to swap the pointers they hold.
Code:
//member function
void swap(SmartPtr<T>& other)
{
std::swap(ptr, other.ptr);
}
You might also implement a free swap function (in terms of member swap), which will hopefully get picked up, for example, when a standard algorithm needs to swap your SmartPtr instances.
And now assignment operator would be implemented like this:
Code:
SmartPtr<T>& operator=(const SmartPtr<T>& right)
{
//this takes care of incrementing ref-count on right
SmartPtr<T> temp(right);
//swap contents of left-hand instance and the local copy
swap(temp);
return *this;
//destructor of temp takes care of decrementing ref-count on the pointer previously held by *this
}
(It would also be possible to accept right by value: then temp won't be needed, since a copy will be automatically made.)