为什么推荐加const或constexpr修饰常量

摘要

本文通过代码示例和汇编分析,解释了在C++中使用const或constexpr修饰常量的优势。作者指出,这些修饰符可以避免额外的内存占用和赋值操作,从而提高程序性能。同时,文章提到const/constexpr修饰的常量在反汇编后可能暴露其值,存在一定的安全性问题。通过对比未修饰和修饰后的代码,作者直观地展示了性能优化的效果。



const/constexpr修饰常量可以减少内存占用和拷贝操作.

这是我们在很多书上可以看到的结论, 但是为什么用const/constexpr修饰常量可以减少内存占用和拷贝操作呢?

测试

不使用const/constexpr修饰

我们先来看一个反例, 不使用const/constexpr修饰常量:

1
2
3
4
5
6
7
8
9
using namespace std;

int num = 10;

int main()
{
    int get_num = num;
    return 1;
}

我们可以得到汇编代码:

1
2
mov    eax,DWORD PTR [rip+0x2f1c]        # 404028 <num>
mov    DWORD PTR [rbp-0x4],eax

上面的汇编代码是int get_num = num;这一句, num被放在内存中, 先给寄存器eax, eax再将值赋给get_num.

在这里, 我们消耗了sizeof(int)的内存空间, 多了一个赋值操作.

使用const/constexpr修饰

1
2
3
4
5
6
7
8
9
using namespace std;

const int num = 10;

int main()
{
    int get_num = num;
    return 1;
}

int get_num = num;汇编后:

1
mov    DWORD PTR [rbp-0x4],0xa

num的值直接赋值给get_num, 没有额外的内存占用, 没有额外的赋值操作.

但是, 使用const/constexpr修饰会让常量暴露出来(反汇编程序之后, 我们可以直接知道常量值是多少), 安全性较低.