那麼這裏是我的異常代碼:C++古怪的字符串/字符*異常行爲
class OptionNotFoundError: public std::exception {
public:
OptionNotFoundError(std::string option, int position) throw()
: option(option), position(position) {}
OptionNotFoundError(char option_, int position) throw()
: position(position) { option.push_back(option_); }
virtual ~OptionNotFoundError() throw() {}
virtual const char* what() const throw() {
std::string what_str = "Option '" + option + "' not found in position " + std::to_string(position);
std::cout << what_str.c_str() << std::endl;
return what_str.c_str();;
}
std::string option;
int position;
};
當異常被拋出,這裏是我的終點站下車:
terminate called after throwing an instance of 'Args::OptionNotFoundError'
Option 'c' not found in position 1
what():
所以cout
工作正常,但...不是回報。如果我使用return "smth"
它工作正常。
怪異:如果我
std::string what_str = "test";
更換what_str定義我得到
terminate called after throwing an instance of 'Args::OptionNotFoundError'
test
what(): x�zL�
再次,cout<<
工作正常。但是回報...並不是那麼多。這是一些編碼錯誤?
有這個UB的重複噸... – dasblinkenlight
考慮使用'std :: string what_str;''OptionNotFoundError'類的成員變量而不是'what()'函數內的局部變量。然後'what_str'仍然活着並踢,而不是在返回時被摧毀。 – PaulMcKenzie