gpt4 book ai didi

testing - C++0x : noexcept(ndebug) for testing?

转载 作者:行者123 更新时间:2023-11-28 19:59:32 24 4
gpt4 key购买 nike

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

考虑:

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

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

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

#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];
}

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

最佳答案

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

也就是说,noexcept(ndebug) 对我来说似乎是合理的。我认为没有理由将它隐藏在宏后面。模板函数通常具有冗长的 noexcept 条件。

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

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

关于testing - C++0x : noexcept(ndebug) for testing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7371865/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com