【发布时间】:2015-05-17 03:21:48
【问题描述】:
Standard library defect #254 涵盖了新异常构造函数的添加:
std::logic_error::logic_error(const char* what_arg);
std::runtime_error::runtime_error(const char* what_arg);
// etc.
给出的基本原理是,存储 std::strings 会打开一些与潜在的内存分配问题相关的蠕虫。
但是,following initiation of a discussion by orlp in the Lounge,令我震惊的是,除非标准要求 what_arg 只是一个字符串文字(或指向其他静态存储持续时间缓冲区的指针),否则它必须执行复制无论如何,为了保持成员函数what()的明确定义。
那是因为:
void bar() {
char buf[] = "lol";
throw std::runtime_error(buf);
}
void foo() {
try {
bar();
}
catch (std::exception& e) {
std::cout << e.what() << '\n'; // e.what() points to destroyed data!
}
}
但我看不到任何这样的授权。事实上,异常对象是否深拷贝what_arg 似乎完全没有说明。
如果他们这样做,那么首先添加重载(消除额外分配)的大部分理由似乎完全是空洞的。
这可能是一个标准缺陷,还是我在这里遗漏了什么?
这只是“程序员:不要在任何地方传递悬空指针”的一个例子吗?
【问题讨论】:
标签: c++ exception c++11 language-lawyer