我已经编写了以下代码来测试跨函数调用的 noexcept
传播,它似乎并没有像我想象的那样工作。在 GCC 4.7.2 中,可以有效地测试函数是否为 noexcept
仅直接或作为模板特化参数传递时;但不是当作为参数传递给模板函数时,或作为指向普通函数的函数指针时——即使该函数将其形式参数声明为noexcept
。这是代码:
#include <iostream>
#define test(f) \
std::cout << __func__ << ": " #f " is " \
<< (noexcept(f()) ? "" : "not ") \
<< "noexcept\n";
template <void(*f)()>
static inline void test0() {
test(f);
}
template <typename F>
static inline void test1(F f) {
test(f);
}
static inline void test2(void(*f)()) {
test(f);
}
static inline void test3(void(*f)()noexcept) {
test(f);
}
void f1() {}
void f2() noexcept {}
int main() {
test(f1);
test(f2);
test0<f1>();
test0<f2>();
test1(f1);
test1(f2);
test2(f1);
test2(f2);
test3(f1);
test3(f2);
return 0;
}
这是输出:
main: f1 is not noexcept main: f2 is noexcept test0: f is not noexcept test0: f is noexcept test1: f is not noexcept test1: f is not noexcept test2: f is not noexcept test2: f is not noexcept test3: f is not noexcept test3: f is not noexcept
为什么 noexcept
ness 在其他情况下不传播?在 test1
的情况下,整个函数是用 F
的正确类型“实例化”的,编译器此时肯定知道 F 是否是 noexcept
功能。当完全忽略 noexcept
ness 声明时,为什么可以按照我写的方式编写 test3
?
标准是否必须对此有具体说明?
最佳答案
C++11 标准的第 15.4.13 节指出“异常规范不被视为函数类型的一部分”。
关于c++ - 在传递函数指针时是否应该转发有关 noexcept-ness 的知识?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14003502/