const & constexpr

首先用几个简单的例子来说明一下两者的基本使用,就可以看出来相同点和不同点了。

const主要在于:只读

constexpr顾名思义常量表达式:常量

1)只读 | 常量

cpp 复制代码
#include <iostream>
#include <array>

using namespace std;

void dis_1(const int x) {
    array<int, x> myarr{1, 2, 3, 4, 5}; // 错误,x是只读的变量(本质仍未变量)
    cout << myarr[1] << endl;
}

void dis_2() {
    const int x = 5;                    // 正确,只读变量的同时,还是一个值为5的常量
    array<int, x> myarr{1, 2, 3, 4, 5};
    cout << myarr[1] << endl;
}

int main()
{
    dis_1(5);
    dis_2();
}

2)"只读" 与 "不允许被修改" 的区别:

cpp 复制代码
#include <iostream>

using namespace std;

int main()
{
    int a = 10;
    const int& con_b = a;
    cout << con_b << endl;    // 10
    a = 20;
    cout << con_b << endl;    // 20
}

3)const & constexpr区别:

cpp 复制代码
#include <iostream>
#include <array>

using namespace std;

constexpr int sqr1(int arg) {
    return arg*arg;
}

const int sqr2(int arg) {   // warning: 'const' type qualifier on return type has no effect
    return arg*arg;
}

int main()
{
    array<int, sqr1(10)> mylist1;   // 可以,因为sqrt1是constexpr函数
    array<int, sqr2(10)> mylist2;   // 不可以,因为sqrt1不是constexpr函数
    return 0;
}

总的来说在 C++ 11 标准中,const 用于为修饰的变量添加"只读"属性;而 **constexpr**关键字则用于指明其后是一个常量(或者常量表达式),编译器在编译程序时可以顺带将其结果计算出来,而无需等到程序运行阶段,这样的优化极大地提高了程序的执行效率。

相关推荐
AA陈超1 天前
ASC学习笔记0020:用于定义角色或Actor的默认属性值
c++·笔记·学习·ue5·虚幻引擎
coderxiaohan1 天前
【C++】仿函数 + 模板进阶
开发语言·c++
思成不止于此1 天前
深入理解 C++ 多态:从概念到实现的完整解析
开发语言·c++·笔记·学习·多态·c++40周年
布丁写代码1 天前
GESP C++ 一级 2025年09月真题解析
开发语言·c++·程序人生·学习方法
喵个咪1 天前
Qt 优雅实现线程安全单例模式(模板化 + 自动清理)
c++·后端·qt
欧阳x天1 天前
C++入门(一)
c++
小张成长计划..1 天前
【C++】:priority_queue的理解,使用和模拟实现
c++
Dream it possible!1 天前
LeetCode 面试经典 150_二叉树层次遍历_二叉树的层平均值(82_637_C++_简单)
c++·leetcode·面试·二叉树
云泽8081 天前
C++ List 容器详解:迭代器失效、排序与高效操作
开发语言·c++·list
xlq223221 天前
15.list(上)
数据结构·c++·list