I'm deriving my own exception, call it MyException
, from std::system_error
and have overridden what()
to calculate and return my message. MyException
's initializer list doesn't call the system_error constructor override that takes a message.
If I catch a MyException
and copy it to a std::exception
the result of calling what()
on the std::exception
is nullptr
. This makes sense.
My question is, if I do use the constructor of system_exception that takes a message when initializing MyException
, is it specified that system_error will take a copy of the message and own it and free it?
I'm assuming this would enable a std::exception
copy of MyException
to be able to return a valid what()
. Although I would take a performance hit in that the 'what' needs calculating every time a new one of MyExceptions
is created; I can't lazily calculate it only when what() is first called.
I'm slightly worried about the ownership of the 'what' string as what()
returns a char*
and not a const std::string&
.
The code is something like this (I haven't compiled this):
class MyException : public std::system_error
{
std::string what_;
public:
MyException(int errorValue, const std::error_category& category)
: std::system_error(errorValue, category)
{}
char* what() const
{
what_ = "MyException: " + to_string(code().value());
return what_.c_str();
}
};
int main()
{
std::exception ex;
try
{
throw MyException(4, system_category());
}
catch( const MyException& e )
{
ex = e;
}
printf("what= %s", ex.what());
return 1;
}