【问题标题】:gcc 4.9.1 not standard compliant? (std::runtime_error)gcc 4.9.1 不符合标准? (std::runtime_error)
【发布时间】:2016-09-22 14:53:39
【问题描述】:

我们希望有一个自己的std::runtime_error:runtime_error(const string& arg) 定义。我们根据另一个构造函数来实现这样的构造函数,即std::runtime_error:runtime_error(const char*),例如:

namespace std {
  runtime_error::runtime_error(const string& arg)
    : runtime_error(arg.c_str()) {
    ...
  }
}

使用 gcc-4.9.1,这是不可能的,因为构造函数 std::runtime_error::runtime_error(const string& arg) 不存在。在 gcc/4.9.1/include/c++/4.9.1/stdexcept 中,我们看到以下内容:

...
class runtime_error : public exception 
{
  string _M_msg;
  public:
  /** Takes a character string describing the error.  */
  explicit 
  runtime_error(const string& __arg);
  virtual ~runtime_error() _GLIBCXX_USE_NOEXCEPT;
  /** Returns a C-style character string describing the general cause of
  *  the current error (the same string passed to the ctor).  */
  virtual const char* 
  what() const _GLIBCXX_USE_NOEXCEPT;
};
...

标准明确规定应该有一个显式的runtime_error(const char*) 构造函数。

19.2.6 类 runtime_error [runtime.error]

namespace std {
class runtime_error : public exception {
public:
explicit runtime_error(const string& what_arg);
explicit runtime_error(const char* what_arg);
};

【问题讨论】:

  • "我们按照其他构造函数来实现这样的构造函数" 你为什么要这样做?采用std::string 的那个有一个内置的长度,而另一个必须做一个strlen 来计算长度。那只是无意义的浪费时间。此外,您不能在标准库中重写类。
  • 试一试:直到gcc 4.9.4 才能编译(使用-std=c++11),从gcc 5.1clang 3.5 工作
  • @blackpen C++ 标准不允许,因为 namespace std(以及,从 C++17 开始,namespace std[someNumber])是特殊的。
  • @πάνταῥεῖ c++11 在 4.9 中默认不开启。
  • 当整个程序的行为未定义时,争论标准合规性似乎毫无意义。

标签: c++ c++11 gcc4.9


【解决方案1】:

也许这不能回答你原来的问题,但如果真的是为了拦截 runtime_error 实例化,你可以这样做(假设使用 gcc):

namespace std {
  runtime_error::runtime_error(const string& arg)
  #if (__GNUC__ > 4)
    : runtime_error(arg.c_str())
  #else
    : _M_msg(arg)
  #endif
  {
    // intercept here!
  }
}

希望被调用的runtime_error(const char*) 将来不会以runtime_error(const string&) 的形式实现,这会破坏你所有的希望和愿望。 =)

【讨论】:

    猜你喜欢
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 2011-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多