【发布时间】:2018-05-21 16:42:14
【问题描述】:
假设我在某处定义了这些函数:
std::string ws_to_s(const wchar_t*);
std::string ws_to_s(const std::wstring&);
std::wstring s_to_ws(const char*);
我写了这门课:
class runtime_error_w : public std::runtime_error {
public:
runtime_error_w() = default;
runtime_error_w(const wchar_t* what_arg)
: runtime_error(ws_to_s(what_arg)) { }
runtime_error_w(const std::wstring& what_arg)
: runtime_error(ws_to_s(what_arg)) { }
virtual const std::wstring what_w() const noexcept {
return ws_to_s(what());
}
};
到目前为止,这对我有用,但是这种方法有什么问题吗?
注意what_w() 返回一个std::string 对象,而不是const char*。
【问题讨论】:
-
一个潜在的问题是构造
wstring可能会抛出bad_alloc,如果它发生在处理原始异常的过程中就会出现问题。 -
正确,但should I worry 大约是
bad_alloc? -
是的,你应该担心 bad_alloc。不处理异常并让它逃逸到通用的未捕获异常处理程序,同时让 RAII 和堆栈展开确保数据一致性是一回事。使代码调用 std::terminate 并可能丢失数据是另一回事。
标签: c++ c++11 exception wstring