CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List

Select topics to narrow your question pool, then enable Random to jump to a random question matching your filters.

Topics:
C++ Quiz #150

Why m_text.c_str() Is Safe in what()

mediumExceptions

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>
4 
5class 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};
12 
13int 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}