I've seen some smart pointers implementing operator=
in two ways:
A) One that assigns the raw pointer to the other raw pointer:
SmartPointer& operator=(const SmartPointer& rhs)
{
delete m_ptr;
m_ptr = rhs.m_ptr;
return *this;
}
B) And one that nullifies the right hand side's pointer after the assignment:
SmartPointer& operator=(SmartPointer& rhs)
{
delete m_ptr;
m_ptr = rhs.m_ptr;
rhs.m_ptr = nullptr
return *this;
}
My question would be which one is more advised to be used? My problem with B) is that if one may want to further operate on the second smart pointer (see code below), the program would crash (if not checking for null pointer) or do nothing. And that doesn't seem too nice :)
SmartPointer<MyClass> p1(new MyClass());
SmartPointer<MyClass> p2(new MyClass());
p1 = p2;
p2->someMethod(); // <----- BOOM!