【发布时间】:2016-04-05 23:29:12
【问题描述】:
constexpr 说明符是否暗示函数的 noexcept 说明符? Answer 到 the similar question 对 inline 说明符说“是”,但 Eric Niebler's article 让我想知道当前问题的可能答案。在我看来,答案可能取决于使用 constexpr 函数的上下文:它是常量表达式上下文还是运行时上下文,即函数的所有参数在编译时是否已知。
我预计答案是“是”,但simple check 表明事实并非如此。
constexpr
bool f(int) noexcept
{
return true;
}
constexpr
bool g(int)
{
return true;
}
static_assert(noexcept(f(1)));
static_assert(noexcept(g(2))); // comment this line to check runtime behaviour
#include <cassert>
#include <cstdlib>
int
main(int argc, char * [])
{
assert(noexcept(f(argc)));
assert(noexcept(g(argc)));
return EXIT_SUCCESS;
}
【问题讨论】:
-
@cad 无论如何这个问题很笼统,不要认为有很好的具体例子。
-
反例:
constexpr void * foo(int n) { return n == 0 ? nullptr : operator new(n); }。 Demo. -
我确实滥用过一次,请参阅stackoverflow.com/a/13305072/34509
-
这不是真的,对have throws in a constexpr function有效,下面也看我的回答。
-
查看我的更新答案,我们有一份缺陷报告可以解决这个确切的问题。
标签: c++ inline c++14 constexpr noexcept