Re: Should the assignment of an exception class call std::exception::operator=?
Niels Dekker - no return address ha scritto:
Should the assignment operator of a custom exception class derived from
std::exception, do an std::exception assignment? For example:
Any derived class implementing operator= should call the inherited
operator= in a way or another. It's not a matter of style, omitting to
do so would produce incorrect results.
class MyException : public std::exception
{
public:
MyException & operator=(const MyException & arg)
{
// Good Coding Style?
static_cast<std::exception &>(*this) = arg;
return *this;
}
};
I actually recall I saw this as a "recommended" idiom somewhere. A
better syntax avoiding the cast would be:
std::exception::operator=(arg);
but it's known to confuse some older compilers, especially when the base
class does not define operator= explicitly.
I'm asking because there's a bug in the std::exception::operator=
implementation I'm currently using, as reported by Jouni Kiviniemi at
connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=328570
Ugh. Then discussing whether the above approach is good style or not is
totally pointless, because such approach doesn't solve your problem. In
fact you will still be calling std::exception::operator= even if the
syntax may look exotic.
Actually it caused a unit test crash in a revision of ITK's
ExceptionObject class <www.itk.org> that I committed last week. So I
think I have to remove the std::exception::operator= call anyway...
You are facing a lost battle. If you don't call the base operator= the
code will produce the wrong result, because you won't be copying the
string to the target object. Yet, if you do call operator= you have a
memory leak...
Given that this is a bug Microsoft should fix, the only workaround is to
avoid calling std::exception::operator=. For example:
class MyException : public std::exception
{
public:
MyException & operator=(const MyException & arg)
{
if (this != arg)
{
// This is only to work around a bug in the base class
// NOT a generally valid approach to assignment
this->~MyException();
new(this) MyException(arg.what());
}
return *this;
}
};
Not the best code, but I've seen worse. And it works, provided
MyException has a constructor that passes its argument to the
constructor of the base class.
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]