I was casually doing some challenges on HackerRank and I stumbled on "Inherited Code", which I’ve tried to solve with this:
class BadLengthException : public exception {
private:
const char* message;
public:
BadLengthException(int n_) {
this->message = to_string(n_).c_str();
}
const char * what() const throw() {
return this->message;
}
};
Since it did not work (the output was empty), I’ve searched on SO the reason why and I found this question on the same problem. I think I do understand the solution proposed, but I’m still very confused about my try:
I get that the string to_string(n_).c_str() could be seen as a local variable, like the example in the mentioned question, but why it’s still treated as such when what() is called? Shouldn’t it have been kept in message via initialization, thus being available whenever calling what()?
>Solution :
const char* is a pointer to a raw C-string. It is not a container object (like std::string) that would own the string and manage the allocation/deallocation of the buffer that contains the string.
to_string(int) returns a std::string with a string representation of the number. Then c_str() returns a pointer to that string.
But in this->message = to_string(n_).c_str();, first a temporary std::string object is constructed, and then message is set to the pointer to that string. But afterwards, the temporary std::string is deleted (which deallocates its buffer), and message is now a dangling pointer, that points to memory that is no longer allocated.
One solution would be to instead make this->message a std::string. And make what() return this->message.c_str().