Reputation: 1649
Answers to other questions say this is how to write assignment for a derived class:
class D : public B
{
public:
D& operator=(const D& other)
{
B::operator=(other);
// D-specific stuff
return *this;
}
};
But shouldn't the usual "check for self assignment" be done? Eg:
class D : public B
{
public:
D& operator=(const D& other)
{
if ( this != &other ) {
B::operator=(other);
// D-specific stuff
}
return *this;
}
};
Or maybe the base class assignment should be left out of the check?
Upvotes: 2
Views: 578
Reputation: 101484
Warning - the following may sound a bit hard-line.
But shouldn't the usual "check for self assignment" be done?
Emphatically, no.
Consider the circumstances under which self-assignment would occur. Something as contrived as:
D d;
d = d;
But the above code is flawed, and should never have been written in the first place. It's the same idea as having a global catch (...)
intended to catch all unhandled exceptions. If that global catch
-all is going to try to continue on as if nothing had happened, all that you are going to get is a nightmare. You won't prevent the program from crashing or doing something even worse (like killing the patient or selling when you should have bought 10k shares of IBM), you just prevented it from crashing right now.
Self-assignment, as in the code sample above, is similarly flawed. Checking for self-assignment and continuing on as if nothing had happened is just sticking your head in he sand, pretending everything is just peachy. The reality is, there is a bug in your code that needs to be fixed.
If self-assignment should never occur, it should (could) be an assert
ion. It should not just roll along. Find and fix the bug that causes self-assignment. Don't code around it.
Upvotes: 4