-1

Is it safe to pass c_str() as a parameter when constructing std::exception? Please let me know if handling exceptions like this is a bad idea. In my project all error messages are returned from a function as std::string and then thrown as a std::exception.

#include <iostream>

int main()
{
    try {
        std::string message="! Something went wrong.";
        throw std::exception(message.c_str());
    }
    catch (std::exception ex) {
        std::cerr << ex.what() << std::endl;
    }
}

1 Answers1

3

std::exception does not have a contructor that takes a const char* or a std::string.

std::runtime_error (and its descendants) does have constructors for both. And yes, it is perfectly safe (well, provided that memory is not low) to pass the message.c_str() pointer to this constructor. std::runtime_error will copy the character data into its own internal memory, allowing message to be destroyed after the exception is thrown.

If you want to throw std::exception itself with a string message, you will have to derive a custom class from it and implement your own string buffer for what() to return a pointer to. In which case, you have to be careful not to return an invalid const char* pointer from what(). std::runtime_error handles that for you, so you should derive from that instead.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770