← Back to Question List
C++ Quiz #150
Why m_text.c_str() Is Safe in what()
what() returns m_text.c_str(). Why is that safe, when writing return (field + ": " + problem).c_str(); directly inside what() would not be?
📄 Code
1#include <iostream>2#include <exception>3#include <string>45class FieldError : public std::exception {6 std::string m_text;7public:8 FieldError(const std::string& field, const std::string& problem)9 : m_text(field + ": " + problem) {}10 const char* what() const noexcept override { return m_text.c_str(); }11};1213int main() {14 try {15 throw FieldError("email", "missing @");16 } catch (const std::exception& e) {17 std::cout << e.what() << "\n";18 }19 return 0;20}