0

This is simplified version of my code:

struct InvalidConfigurationException : public exception {
    InvalidConfigurationException(){}
    const char* what() const throw() {
        return "hi";
    }
};

this returns "hi".

But then if I change this it doesn´t work:

struct InvalidConfigurationException : public exception {
    InvalidConfigurationException(){}
    const char* what() const throw() {
        string hello = "hi";
        return hello.c_str();
    }
};

OUTPUT = Ól< (this is what I get)

This is simplified, but I basically need to return a concatenated string, that´s why I need the c_str(). Can anyone help me?

Lalo Venegas
  • 48
  • 1
  • 4
  • `string hello = "hi";` is a local variable. It expires and goes away at the end of the function. Unfortunately this takes the buffer that `c_str()` returned with it. `hello` must be made to live at least as long as the pointer to the buffer it contains is in use or the pointer refers to an invalid object.. – user4581301 Jun 10 '20 at 00:31
  • @user4581301 thanks for your answer, it made me realize why it didn´t work! – Lalo Venegas Jun 10 '20 at 01:05
  • @JaMiT that´s true, as soon as I changed to string it worked! Thanks :) – Lalo Venegas Jun 10 '20 at 01:05
  • Unfortunately if you change the return type it no longer overrides `exception::what`. If that matters to you, your options here are very limited. You could make the `string` a class member variable and pray that it doesn't throw an exception or make a big `char` array member variable, go old school with `snprintf` and pray that when you allocate the exception you have enough memory to do it. – user4581301 Jun 10 '20 at 02:59

0 Answers0