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()
?
Aucun commentaire:
Enregistrer un commentaire