Here is my exception class:
class Win32Failure : public std::exception { public: Win32Failure( char const* win32_function_name, LONG error_code ); char const* win32_function_name() const { return win32_function_name_; } LONG error_code() const { return error_code_; } virtual char const* what() const; private: std::string GetFormattedMessage() const; char const* win32_function_name_; LONG error_code_; std::string error_text_; }; Win32Failure::Win32Failure( char const* win32_function_name, LONG error_code ) : error_code_(error_code) , win32_function_name_(win32_function_name) { std::stringstream error_msg; error_msg << win32_function_name << " failed with code: " << error_code << " (" << GetFormattedMessage() << ")" ; error_text_ = error_msg.str(); } std::string Win32Failure::GetFormattedMessage() const { TCHAR message_buffer[1000]; FormatMessage(
recommendations for eliminating exceptions recommend not placing any objects that allocate memory as members of my exception class. In this case, using std::string violates this. I respect the rule for this, however I cannot think of a way to implement an override of what() without using std :: string to manage the memory (as opposed to the caller having to manage it for me).
I could use a fixed-size buffer as a member and use C library functions (e.g. snprintf() ) to do the job, but this is not very idiomatic for C ++ and therefore not an ideal solution.
Is this a suitable implementation of the exception class? If not, what improvements can be made?
c ++ design exception exception-handling
void.pointer
source share