【问题标题】:A wstring wrapper to std::runtime_error exception?std::runtime_error 异常的 wstring 包装器?
【发布时间】: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


【解决方案1】:

根据问题下方的 cmets,我同意使用这个类是一个坏主意,因为在构造 wstring 时可能会引发 bad_alloc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    相关资源
    最近更新 更多