gpt4 book ai didi

c++ - C++ 允许 CTFE 吗?

转载 作者:行者123 更新时间:2023-11-30 00:36:18 27 4
gpt4 key购买 nike

测试了一个简单的 utf8 strlen 函数,很惊讶 trunk clang 完全消除了它(gcc 没有):

static int strlenutf8(const char* s)
{
int i = 0, l = 0;
while (s[i])
{
if ((s[i] & 0xc0) != 0x80) l++;
l++;
}
return j;
}

int main()
{
return strlenutf8("bla");
}

clang++ -O3 -S -fverbose-asm:

main:                                   # @main
.cfi_startproc
# BB#0: # %entry
movl $3, %eax
ret

这就像 D 的编译时函数求值。这在 C++ 中是否合法?

我的意思是说到底,他们首先发明那个蹩脚的 constexpr 肯定是有原因的。据我所知,它甚至不能在这里使用,因为它受到严格限制。

最佳答案

constexpr 仅对常量表达式上下文(如模板参数推导)是必需的,但不能保证在编译时评估 constexpr 函数。

优化 C++ 程序的黄金法则是 as-if 规则:

The semantic descriptions in this International Standard define a parameterized nondeterministic abstract machine. This International Standard places no requirement on the structure of conforming implementations. In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained below.

加上非常需要的脚注:

This provision is sometimes called the “as-if” rule, because an implementation is free to disregard any requirement of this International Standard as long as the result is as if the requirement had been obeyed, as far as can be determined from the observable behavior of the program. For instance, an actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no side effects affecting the observable behavior of the program are produced.

有一个主要的但是:具有副作用的复制构造函数(例如,它们递增一个“称为”计数变量或等效的“复制构造函数”)不需要包含在“as-if”中。这包含在 12.8/31 中:

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects. In such cases, the implementation treats the source and target of the omitted copy/move operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later of the times when the two objects would have been destroyed without the optimization.123This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies): [...]

关于c++ - C++ 允许 CTFE 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16195924/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com