C++0x:用于测试的 noexcept(ndebug)?

tow*_*owi 5 testing noexcept c++11

我读到有关过度使用noexcept可能会阻碍可测试库的担忧。

考虑:

T& vector::front() noexcept {
    assert(!empty());         // <- this may throw in some test-frameworks
    return data[0];
}
Run Code Online (Sandbox Code Playgroud)

使用noexcept编译器的注释可能会优化异常代码,这会/可能会阻止正确处理assert()(或作者想在这里使用的任何函数进行测试)。

因此,我想知道,在库中从不使用无条件,noexcept而是始终将其与 am-I-in-a-test-condition “链接”是否可行。像这样:

#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];
}
Run Code Online (Sandbox Code Playgroud)

然后也许将它添加为一个宏(虽然,我讨厌那样):

#define NOEXCEPT noexcept(ndebug)

T& vector::front() NOEXCEPT {
    assert(!empty());
    return data[0];
}
Run Code Online (Sandbox Code Playgroud)

你怎么认为?这有任何意义吗?还是不可行?还是不能解决问题?或者根本没有问题?:-)

spr*_*aff 3

如果您无法证明函数不会发出异常,那么您不应该用 来标记它noexcept。就是这么简单。

noexcept(ndebug)对我来说似乎很合理。我认为没有理由将其隐藏在宏后面。模板函数通常具有详细的noexcept条件。

如果资产中的函数可以在测试模式期间抛出异常,那么您的程序可以std::terminate在测试模式期间自发抛出异常。(实际上,这很像隐式assert。)

我能看到的唯一缺点是,如果发生这种情况,您将不会收到行号和提示消息。noexcept(false)如果您从一个函数调用一个函数,编译器应该警告您noexcept(true),这样您可能会收到一些噪音。