Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用const&;用于重新标记变量的类型_C++_Variables_Reference_Names - Fatal编程技术网

C++ 使用const&;用于重新标记变量的类型

C++ 使用const&;用于重新标记变量的类型,c++,variables,reference,names,C++,Variables,Reference,Names,我喜欢使用const&type T=LongVariableName在一小段代码中重新标记变量,尤其是涉及公式的代码 例如: const double& x = VectorNorm; double y = a*x*x*x + b*x*x + c*x + d; 我认为编译器应该足够聪明,可以优化这些引用变量。这几乎总是会发生吗?什么时候可以呢?这取决于编译器和您设置的优化选项-不能保证它会或不会被优化掉。启用了优化功能的现代编译器可能会对其进行优化,但更好的问题是:您是否应该在意?除非

我喜欢使用
const&type T=LongVariableName
在一小段代码中重新标记变量,尤其是涉及公式的代码

例如:

const double& x = VectorNorm;
double y = a*x*x*x + b*x*x + c*x + d;

我认为编译器应该足够聪明,可以优化这些引用变量。这几乎总是会发生吗?什么时候可以呢?

这取决于编译器和您设置的优化选项-不能保证它会或不会被优化掉。启用了优化功能的现代编译器可能会对其进行优化,但更好的问题是:您是否应该在意?除非你处于每秒数千次的紧张循环中,否则别担心。代码清晰性通常比减少几个时钟周期更重要

无论如何,让我们看一看。我通过MinGW使用GCC4.7.2。我们将使用以下代码:

so.cpp:

#include <cstdio>

int main()
{
    float aReallyLongNameForAVariable = 4.2;
#ifdef SHORT_REF
    const float& x = aReallyLongNameForAVariable;
    float bar = x * x * x;
#else
    float bar = aReallyLongNameForAVariable * aReallyLongNameForAVariable * aReallyLongNameForAVariable;
#endif
    printf("bar is %f\n", bar);
    return 0;
}
现在让我们使用参考:

g++ -DSHORT_REF -S -masm=intel -o ref.S so.cpp

call    ___main
mov eax, DWORD PTR LC0
mov DWORD PTR [esp+20], eax
lea eax, [esp+20]
mov DWORD PTR [esp+28], eax
mov eax, DWORD PTR [esp+28]
fld DWORD PTR [eax]
mov eax, DWORD PTR [esp+28]
fld DWORD PTR [eax]
fmulp   st(1), st
mov eax, DWORD PTR [esp+28]
fld DWORD PTR [eax]
fmulp   st(1), st
fstp    DWORD PTR [esp+24]
fld DWORD PTR [esp+24]
fstp    QWORD PTR [esp+4]
mov DWORD PTR [esp], OFFSET FLAT:LC1
call    _printf
mov eax, 0
leave
因此,这是一个更大的组装。但是当我们打开优化时会发生什么呢

g++ -DSHORT_REF -O2 -S -masm=intel -o ref.S so.cpp
g++ -O2 -S -masm=intel -o noref.S so.cpp
两者都生成相同的部件:

g++ -S -masm=intel -o noref.S so.cpp

call    ___main
mov eax, DWORD PTR LC0
mov DWORD PTR [esp+28], eax
fld DWORD PTR [esp+28]
fmul    DWORD PTR [esp+28]
fmul    DWORD PTR [esp+28]
fstp    DWORD PTR [esp+24]
fld DWORD PTR [esp+24]
fstp    QWORD PTR [esp+4]
mov DWORD PTR [esp], OFFSET FLAT:LC1
call    _printf
mov eax, 0
leave
call    ___main
fld DWORD PTR LC0
fstp    QWORD PTR [esp+4]
mov DWORD PTR [esp], OFFSET FLAT:LC1
call    _printf
xor eax, eax
leave

好了。现代编译器(至少是gcc)优化了引用。

顺便说一句,
((a*x+b)*x+c)*x+d
可能比你的公式快。另外,我会去掉引用,只写
双x=VectorNorm