问题描述
这些可能应该在不同的问题中,但是它们是相关的……
-
为什么我们要写
constexpr
呢?给定一组限制,编译器无法评估代码以查看其是否满足constexpr
的要求,并将其视为constexpr
是否这样做?作为纯粹的文档关键字,我不确定它是否成立,因为我无法想到我(其他人constexpr 函数)应该真的在乎它是否在运行。
这是我的逻辑:如果这是一个昂贵的函数,我认为按照惯例,我应该这样处理不管我是否给它编译时常量输入。这可能意味着在加载时调用它并保存结果,而不是在执行的关键时刻调用它。原因是因为
constexpr
实际上并没有向我保证它不会在一开始就在运行时执行-因此也许应该有一个新的/不同的机制来执行。
-
似乎排除了很多(如果不是大多数的话)函数,这些函数在逻辑上可以我已经读过这至少部分(或全部?)是为了防止无限循环和挂起编译器。但是,如果这是 原因,那是否合法?
编译器是否能够针对使用给定输入的任何给定
constexpr
函数计算出是否无限循环?这不是解决问题的的方法 em>输入。 constexpr
函数的输入是编译时间常数且是有限的,因此编译器只需要检查有限输入的无限循环:实际使用的输入。 如果您编写编译时无限循环,则应该是常规编译错误。
解决方案
I问了一个非常相似的问题,
何时一位Clang作家Richard Smith,他解释说:
This all didn't seem convincing at first, but if you work through the details, things do unravel without constexpr
. A function need not be instantiated until it is ODR-used, which essentially means used at runtime. What is special about constexpr
functions is that they can violate this rule and require instantiation anyway.
Function instantiation is a recursive procedure. Instantiating a function results in instantiation of the functions and classes it uses, regardless of the arguments to any particular call.
If something went wrong while instantiating this dependency tree (potentially at significant expense), it would be difficult to swallow the error. Furthermore, class template instantiation can have runtime side-effects.
Given an argument-dependent compile-time function call in a function signature, overload resolution may incur instantiation of function definitions merely auxiliary to the ones in the overload set, including the functions that don't even get called. Such instantiations may have side effects including ill-formedness and runtime behavior.
It's a corner case to be sure, but bad things can happen if you don't require people to opt-in to constexpr
functions.
As for constexpr
objects, certain types can produce core constant expressions which are usable in constant expression contexts without having been declared constexpr
. But you don't really want the compiler to try evaluating every single expression at compile time. That's what constant propagation is for. On the other hand it seems pretty essential to document when something needs to happen at compile time.
这篇关于为什么在适用时不暗示constexpr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!