C++20新特性—consteval与constinit

consteval可用在立即函数(immediate function),立即函数实际上是编译时运行的函数,也就是它的参数在编译时是“确定的”(常量),它的结果也是常量。constexpr可用于编译或运行时函数,它的结果是常量。它们区别如下例,特别注意的是注释掉的那行。

using namespace std;
consteval int compileconst(int n) { return n+1;}
constexpr int runcompileconst(int n)  { return n+1;}
int main() 
{
    int nn= compileconst (100);
   cout <<nn<<endl;
   // int nnn= compileconst (nn);   //error , nn is not const
    int nnn= runcompileconst (nn);
    cout<<nnn; 
    return 0;
}

constinit variable表示该变量在程序(线程)开始就被分配的,与程序(线程)具有相同的生命周期,因此它有点static的意思,在编译时被初始化。下面例子中被注释掉的两行会产生编译错误,从中可以看出,constexpr的变量是const类型,只读,constinit是说变量在程序开始时被初始化,是static类型,不能在运行时被创建,变量不要求是const类型。

using namespace std;
consteval int sqr(int n) {  return n * n;}
constexpr int res1 = sqr(5);
constinit int res2 = sqr(5); 
int main() {

cout << res1 <<endl;
// cout<<++res1<<endl;   // error: increment of read-only variable 'res1'
cout << res2 <<endl;
cout<<++res2<<endl;
//constinit  auto res3 = sqr(5);   // error: 'constinit' can only be applied to a variable with static or thread storage duration
    constinit thread_local auto res3 = sqr(5);     
    cout << res3 <<endl;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值