我读到过关于过度使用noexcept可能会妨碍可测试库的担忧。
考虑:
T& vector::front() noexcept {
assert(!empty()); // <- this may throw in some test-frameworks
return data[0];
}使用带有noexcept的注释,编译器可以优化异常代码输出,这将/可能妨碍正确处理assert() (或作者希望在这里用于测试的任何函数)。
因此,我想知道,在一个库中,不使用无条件的noexcept,而是始终将其与测试条件中的am-i连接起来,在库中使用是否可行。如下所示:
#ifdef NDEBUG // asserts disabled
static constexpr bool ndebug = true;
#else // asserts enabled
static constexpr bool ndebug = false;
#end
T& vector::front() noexcept(ndebug) {
assert(!empty());
return data[0];
}然后可能将其添加为宏(尽管,我讨厌这样做):
#define NOEXCEPT noexcept(ndebug)
T& vector::front() NOEXCEPT {
assert(!empty());
return data[0];
}你认为如何?这有什么意义吗?还是不可行?还是它解决不了问题?或者根本没有问题?
发布于 2011-09-19 12:44:23
如果不能证明一个函数不会发出异常,那么就不应该用noexcept标记它。就这么简单。
尽管如此,noexcept(ndebug)在我看来是合理的。我看不出有什么理由把它藏在宏后面。模板函数通常具有冗长的noexcept条件。
如果资产中的函数可以在测试模式期间抛出,那么程序可以在测试模式期间自发地抛出std::terminate。(实际上它很像一个隐式assert。)
我能看到的唯一缺点是,如果发生这种情况,您将不会得到一个行号和提示消息。如果您从noexcept(false)函数调用noexcept(true)函数,那么编译器应该警告您,这样您可能会得到一些噪音。
https://stackoverflow.com/questions/7371865
复制相似问题