【发布时间】:2017-01-11 12:29:18
【问题描述】:
这是我的异常代码:
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",它可以正常工作。
更奇怪的是:如果我将 what_str 定义替换为
std::string what_str = "test";
我明白了
terminate called after throwing an instance of 'Args::OptionNotFoundError'
test
what(): x�zL�
同样,cout<< 工作正常。但是回报……没有那么多。这是一些编码错误吗?
【问题讨论】:
-
这个 UB 有大量重复项...
-
考虑将
std::string what_str;设为OptionNotFoundError类的成员变量,而不是what()函数内部的局部变量。然后what_str将仍然活着并踢而不是在返回时被摧毁。
标签: c++ arrays string exception stdstring