0

I have the following custom NotImplementedException Class.

#include <stdexcept>

#ifndef NOT_IMPLEMENTED_EXCEPTION_H
#define NOT_IMPLEMENTED_EXCEPTION_H

class NotImplementedException : public std::logic_error {

private:

    std::string m_message, m_function;

public:

    NotImplementedException(const char* function);
    ~NotImplementedException();

    virtual const char* what() const;

};

#endif


#include "NotImplementedException.h"

NotImplementedException::NotImplementedException(const char* function) : 
std::logic_error("NotImplementedException"), m_message("Function not 
implemented: "), m_function(function) {}

NotImplementedException::~NotImplementedException() {}

const char* NotImplementedException::what() const {

    std::logic_error::what();
    return (m_message + m_function).c_str();

}

I utilize this exception in the following function.

virtual double Delta() const {
    throw NotImplementedException(__FUNCTION__);
}

Here is the test in the main class:

try {

    std::cout << option.Delta() << std::endl;

}
catch (std::logic_error& ex) {
    std::cout << ex.what() << std::endl;
}

Print out from Console: enter image description here

I don't understand why it is printing the message from what() like that. If for example, I change the function signature to std::string what() then the message prints out correctly. Am I printing out a char* incorrectly?

Mutating Algorithm
  • 2,604
  • 2
  • 29
  • 66
  • 1
    TL;DR of the dupe: `(m_message + m_function)` is a temporary. You can never return a pointer/reference to a temporary. – NathanOliver Jul 15 '19 at 20:50
  • @NathanOliver it's a real pity that compilers do not seem to be able to see that and issue a warning. – SergeyA Jul 15 '19 at 20:58
  • When you perform `m_message + m_function`, you need to save the result to a `std::string` member and then have `what()` call `c_str()` on that member. The result of the concatenation needs to outlive any invocation of `what()` – Remy Lebeau Jul 16 '19 at 01:27

0 Answers0