I’ve written a custom exception class to deal with OLE automation errors. The what() method looks like this:
const char* OleException::what() const throw() {
std::string res = std::runtime_error::what();
LPTSTR errorText = NULL;
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
hresult,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&errorText,
0,
NULL);
if(NULL != errorText) {
res = res + " - " + errorText;
LocalFree(errorText);
}
//std::cout << res << std::endl;
return res.c_str();
}
However, when I try to print the string it returns in my main() function, all I get is the letter “I”. The weird part is: when I uncomment the second-to-last line of the method, it works just fine, i.e. I get the same message twice on my terminal. What am I doing wrong?
As others have pointed out, the pointer returned by
c_stris invalidated the momentwhatreturns, becauseretis then no longer alive.The solution is to make the error message a member of your exception class of type
std::stringand do the formatting at construction time, rather than inwhat. You can then safely return fromc_str.