从C ++ 17开始,std::array<T,N>::begin()
是constexpr:
std::array<T,N>::begin()
但是如何在编译时知道constexpr iterator begin() noexcept;
的返回值?例如:
begin
是完全合法的代码(尽管可能有点用处)。基础数组的开始,因此迭代器取决于malloc的地址。
我有一种误解,认为int main() {
auto p = std::make_unique<std::array<int,2>>();
auto it = p->begin();
}
会做什么,因为我看不到any非静态成员函数可能是constexpr
,特别是如果它(以传递方式)访问数据时成员。
constexpr
函数可以在非编译时常数表达式中调用。此类调用在运行时进行评估。仅当在编译时常数表达式中调用constexpr
函数时,该函数才在编译时求值。
但是如何在编译时知道开始的返回?
可以在编译时知道数组本身是编译时间常数。
[当数组不是编译时间常数时,在编译时无法知道它的事实不是问题,因为在这种情况下,该函数是在运行时执行的。
您不需要唯一的指针即可查看编译时间与运行时评估的效果。确实可以编译:
constexpr
但这不是:
constexpr
错误:
#include <array>
int main() {
static constexpr std::array<int,2> p{1,2};
constexpr auto it = p.begin();
}
草率地说,#include <array>
int main() {
std::array<int,2> p{1,2};
constexpr auto it = p.begin();
}
的<source>:5:18: error: constexpr variable 'it' must be initialized by a constant expression
constexpr auto it = p.begin();
^ ~~~~~~~~~
<source>:5:18: note: pointer to subobject of 'p' is not a constant expression
<source>:4:21: note: declared here
std::array<int,2> p{1,2};
意味着可以在编译时在constexpr
对象上评估该方法。对于非begin()
数组,将在运行时评估该方法。因此,constexpr
无法用于初始化constexpr
。