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**关键字则用于指明其后是一个常量(或者常量表达式),编译器在编译程序时可以顺带将其结果计算出来,而无需等到程序运行阶段,这样的优化极大地提高了程序的执行效率。

相关推荐
樱木Plus1 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit3 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_4 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星4 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛6 天前
delete又未完全delete
c++
端平入洛7 天前
auto有时不auto
c++
哇哈哈20218 天前
信号量和信号
linux·c++
多恩Stone8 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马8 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝8 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode