我写了下面的代码来测试noexcept
跨函数调用的传播,似乎它并不像我想象的那样工作。在 GCC 4.7.2 中,可以有效地测试函数是否被noexcept
仅直接或作为模板专业化参数传递时;但not当作为参数传递给模板化函数时,或者作为函数指针传递给普通函数时——即使该函数将其形式参数声明为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
Why is noexcept
在其他情况下不会传播?的情况下test1
,整个函数是用正确的类型“实例化”的F
,编译器当时肯定知道 F 是否是一个noexcept
功能。为什么可以写test3
按照我写的方式,当noexcept
ness 声明被完全忽略?
标准是否必须对此做出具体规定?
C++11 标准第 15.4.13 节指出“异常规范不被视为函数类型的一部分”。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)