How to create a custom exception with a message?

I am new to C ++ and I am trying to create a custom exception that accepts a message in its ctor.

Now I have the following:

class LevelLoadException : public std::exception { public: LevelLoadException(std::string msg) : m_message(msg) { } const char * what () const throw () { return m_message.c_str(); } private: std::string m_message; }; 

In my code, I have this as part of the switch statements ( c is char, or more specifically c = line[x]; where x is int and line is std::string );

 default: throw LevelLoadException("Invalid Character in Level: " + c); 

The problem is that my Exception gets a completely unrelated string (the part of the same method that throws: throw std::exception("There is more than 1 player start in the level.") ).

I excluded a logical error - my program reaches the line where the correct exception with the correct line is selected. Therefore, I am sure that this is a lifecycle / memory management issue.

As far as I understand, C ++ is copied by value by default. So I thought that calling ctor LevelLoadException would immediately copy the line. But it seems that there is some kind of pointer material, because the line I create looks like a C line ( const char* ).

I looked at the std::exception class, and const char* const& is taken into this message, and then some C-like strcopy / malloc is executed under the hood (MSVC / Visual Studio 2012 Update 4).

I am not one hundred percent sure what I really need. I think what I want is the line that was built in the caller and then moved / copied to Exception (which now owns a copy of the line that belongs only to the exception), and then the one that is in the caller is destroyed when it exits out of scope.

Can someone give me a pointer to what I should do differently to do it right?

+6
source share
1 answer

"Invalid Character in Level: " + c does not do what you think. This means "a char* pointer that shifts N bytes from the beginning of the string literal", where N is the ASCII character code stored in c . Most likely, the literal is actually shorter than the N characters, in which case this program contains a buffer overflow and exhibits undefined behavior.

Do it

 throw LevelLoadException(std::string("Invalid Character in Level: ") + c); 
+12
source

Source: https://habr.com/ru/post/975051/


All Articles