【发布时间】:2019-07-23 05:12:50
【问题描述】:
考虑使用LLVM system_category 实现编写的自定义错误类型以供参考:
#include <iostream>
#include <system_error>
struct my_error_category_type : std::error_category {
char const* name() const noexcept override { return "name"; }
std::string message(int i) const noexcept override{ return "message"; }
~my_error_category_type() {
std::cout << "Destroyed the category" << std::endl;
}
};
std::error_category const& my_error_category() noexcept {
static my_error_category_type c;
return c;
}
现在想象以下使用std::error_code 处理错误的简单类:
std::error_code do_some_setup() {
return std::error_code(1, my_error_category());
}
std::error_code do_some_cleanup() {
return std::error_code(2, my_error_category());
}
struct MyObj {
void method() {
// this constructs the category for the first time
auto err = do_some_setup();
std::cout << err << std::endl;
}
~MyObj() {
std::cout << "Running cleanup" << std::endl;
auto err = do_some_cleanup();
std::cout << err << std::endl;
}
};
以下代码给出报警输出
static MyObj obj;
int main() {
obj.method(); // remove this line, and the output is fine
}
name:1
Destroyed the category
Running cleanup
name:2
注意my_error_category_type::message 是如何在被破坏的对象上调用的!
我的问题是:
- 在这个被破坏的对象上调用
message安全吗? - 如果没有,有没有办法保留类别的生命周期?我能以某种方式使对象不朽吗?
- 标准是否对内置
std::system_category()对象等的生命周期做出任何保证?我在上面链接到的 LLVM 实现遇到了完全相同的问题。
【问题讨论】:
-
看起来像 1 的答案。might be yes
标签: c++ c++11 language-lawyer std-system-error