c++ - 在传递函数指针时是否应该转发有关 noexcept-ness 的知识?

标签 c++ c++11 noexcept

我已经编写了以下代码来测试跨函数调用的 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

为什么 noexceptness 在其他情况下不传播?在 test1 的情况下,整个函数是用 F 的正确类型“实例化”的,编译器此时肯定知道 F 是否是 noexcept功能。当完全忽略 noexceptness 声明时,为什么可以按照我写的方式编写 test3

标准是否必须对此有具体说明?

最佳答案

C++11 标准的第 15.4.13 节指出“异常规范不被视为函数类型的一部分”。

关于c++ - 在传递函数指针时是否应该转发有关 noexcept-ness 的知识?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14003502/

相关文章:

c++ - 在共享内存中移动 boost::interprocess::string

c++ - d'tor 的函数尝试 block 是否应该允许处理抛出成员变量 d'tor?

c++ - 声明内联函数 noexcept 有意义吗?

c++ - 将 pardiso 求解器与特征一起使用

c++ - 如果通过委托(delegate)给 `free` 的重载 `new[]` 分配内存,那么 `malloc` 内存是否安全?

c++ - 如何从类定义中省略私有(private)非虚拟方法?

c++ - 尝试学习 boost::intrusive Q3 - 在 IC 中存储指针时,我应该使用 smart_pointer 吗?

c++ - lambda 表达式的 noexcept 和空抛规范之间有什么区别吗?

c++ - 使用命名空间标准和模板类

c++ - 有符号/无符号比较