What and c++ exception -


i tried create custom exception class printing helpful message's sakes:

#include <iostream> #include <algorithm> #include <iomanip> #include <vector> #include <sstream> #include <cstdlib>  class invalid_input_exception : public std::exception { private:     const char* input; public:     invalid_input_exception(const char *);     const char* what() const noexcept; };  invalid_input_exception::invalid_input_exception(const char * input) : input(input) { }  const char * invalid_input_exception::what() const noexcept {     std::string message;     message.append("occured on: ")             .append(input);     return message.c_str(); }  int main(int argc, char ** argv) {     const char* str = "aaaaa";     throw invalid_input_exception(str); } 

but doesn't excatly work because after throwing instance of invalid_input_exception what() message empty.

demo

what wrong?

 return message.c_str(); 

message local function, , you're returning pointer internal buffer. undefined behaviour ensues.


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -