gpt4 book ai didi

c++ - 将数学计算写成变量初始化中常量表达式的值会增加计算量吗?

转载 作者:行者123 更新时间:2023-11-30 01:17:08 25 4
gpt4 key购买 nike

在 C++ 中,常量变量初始化中的数学声明是否需要一些额外的处理?或者现代编译器会在创建 .exe 文件时自动将数学计算的结果放入变量中?

例如:

MyClass::MyClass()
{
const qint32 defaultX = 20;

poButton1 = new PushButton(this);
poButton1->move(defaultX,20);

poButton1 = new PushButton(this);
poButton1->move(defaultX,80);
//...
}

是在方法使用(本例中为构造函数)中使用常量变量 (defaultX) 的代码示例。现在,有时开发人员最好告知值(value)来自何处:

MyClass::MyClass()
{
const qint32 defaultX = 800/2 - 244 + 12 + 32 - 180; //just an example!

poButton1 = new PushButton(this);
poButton1->move(defaultX,20);

poButton1 = new PushButton(this);
poButton1->move(defaultX,80);
//...
}

当然,他可以将其放在评论中,但我们假设他想这样做(例如:他很笨)。那么问题就是:当初始化该类的对象时,是否计算了整个数学表达式(需要额外处理),或者当 .exe 由现代编译器创建时,它已经包含在第一个 MyClass 代码中看到的优化代码?

最佳答案

不能保证,但大多数现代编译器确实会折叠 constant expression , draft C++ standard5.19 Constant expressions 部分有一条注释说在翻译过程中可以计算常量表达式:

[ Note: Constant expressionscan be evaluated during translation.—end note ]

但我们可以在 godbolt 上进行实验使用以下代码:

#include <iostream>
int func()
{
const int defaultX = 800/2 - 244 + 12 + 32 - 180; //just an example!

return defaultX ;
}

int main()
{
std::cout << func() ;
}

并看到它确实将其折叠为以下内容:

func():
movl $20, %eax #,
ret

在 C++11 中你总是可以使用 constexpr确保它在编译时被评估:

constexpr  int defaultX = 800/2 - 244 + 12 + 32 - 180;

该标准确实对浮点常量表达式做出了重要说明。由于缺乏关于浮点运算准确性的规范,因此运行时和编译时的评估可能会产生不同的结果:

[ Note: Although in some contexts constant expressions must be evaluated during program translation, others may be evaluated during program execution. Since this International Standard imposes no restrictions on the accuracy of floating-point operations, it is unspecified whether the evaluation of a floating-point expression during translation yields the same result as the evaluation of the same expression (or the same operations on the same values) during program execution.84 Example:

 bool f() {
char array[1 + int(1 + 0.2 - 0.1 - 0.1)]; // Must be evaluated during translation
int size = 1 + int(1 + 0.2 - 0.1 - 0.1); // May be evaluated at runtime
return sizeof(array) == size;
}

It is unspecified whether the value of f() will be true or false. —end example ] —end note ]

关于c++ - 将数学计算写成变量初始化中常量表达式的值会增加计算量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25189008/

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