Question

When switching compilers my old'n trusted throw code (example below) fails. I'm guessing that it is the err variable scope that is the problem? What happens is that when trying to access the string part of err it has been deallocated. What would be a better way of doing something like this using a custom exception class?

if (someErrorHappend)
{
    std::stringstream err;
    err << "Some error #" << GetLastError() << ".";
    throw SomeCustomException("MyClass", "MyFunc", err.str().c_str());
}
Was it helpful?

Solution

c_str is a non-owning pointer, so you shouldn't pass it to the constructor that will retain it directly.

To fix the problem, simply adjust the constructor SomeCustomException to accept a std::string instead of a char *. The char * will be converted to a string, which is an owning object.

In the future, you can migrate code by removing the c_str() call and leaving only err.str(). The compiler will apply C++11 move semantics to remove one copy operation.

Don't worry about running out of memory. The stringstream code is already allocating on the heap for its internal string, and there's no difference between that and the exception constructor — both run before the throw, and if you ran out of memory beforehand, you should already be in an exception handling state anyway.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top