c++26新功能—几个细节的完善

一、C++26标准的完善

正如前面在分析其它标准时,它分为语言本身的发展和库的发展。语言的特性是真正的C++标准的演进,而库的发展只是语言特性发展的支持或者原来库的完善。C++26做为一个较大版本的演进,极大的增强了C++语言的灵活性、易用性。极大的提高了C++语言的安全性和运行效率。

二、几个具体的细节

在本文中主要对几个比较小的细节进行分析说明,语言特性主要包括:
1、扩展字符集:主要是提供了对@、$和```等字符到基本字符集中,使得代码的可读性和便利性得到了进一步增强
2、constexpr转换:支持了从void*进行constexpr转换,从而在编译期可以支持更多的计算,进而提高了性能
3、占位符变量:这个就比较好理解了,类似其它的语言,用“_”来处理一些不使用或不关心的对象中的属性
标准库的扩展包括:
1、string_view的交互:这个其实就是进一步扩展了string_view与其它字符串类型间的互操作
2、std::is_within_lifetime:主要是用来检查两个对象指针是否在彼此的生命周期内,这样做的结果就是让内存的安全性得到了提高
3、新的SI前缀:为标准库添加新的SI前缀,如std::quecto、std::ronto、std::ronna 和 std::quetta ,方便处理物理量单位

三、例程

看一下相关的例程:

//扩展字符集 
const char* email = "test@ali.com";
const char* coin = "$111";

//constexpr转换
int v = 10;
void* ptrVoid = &v;
constexpr int* ptrInt = static_cast<int*>(ptrVoid);

//占位符
namespace a {
auto _ = f(); // Ok, declare a variable "_"
auto _ = f(); // error: "_" is already defined in this namespace scope
}
void f() {
auto _ = 42; // Ok, declare a variable "_"
auto _ = 0; // Ok, re-declare a variable "_"
{
auto _ = 1; // Ok, shaddowing
assert( _ == 1 ); // Ok
}
assert( _ == 42 ); // ill-formed: Use of a redeclared placeholder variables
}

//string_view交互
std::string s;
std::string_view sv;
convertible_to_string cts;
convertible_to_string_view ctsv;

s + sv;    // OK
s + ctsv;  // OK

s + cts;   // ERROR
cts + sv;  // ERROR

//is_within_lifetime
struct OptBool {
  union { bool b; char c; };

  constexpr OptBool() : c(2) { }
  constexpr OptBool(bool b) : b(b) { }

  constexpr auto has_value() const -> bool {
    if consteval {
      return std::is_within_lifetime(&b);
    } else {
      return c != 2;
    }
  }

  constexpr auto operator*() -> bool& {
    return b;
  }
};

//前缀
using quecto = ratio <1 , 1000000000000000000000000000000 >; // see below
using ronto = ratio <1 , 1000000000000000000000000000 >; // see below
using yocto = ratio <1 , 1000000000000000000000000 >; // see below
using zepto = ratio <1 , 1000000000000000000000 >; // see below
[...]
using zetta = ratio < 1000000000000000000000 , 1 >; // see below
using yotta = ratio < 1000000000000000000000000 , 1 >; // see below
using ronna = ratio < 1000000000000000000000000000 , 1 >; // see below
using quetta = ratio <1000000000000000000000000000000 , 1 >; // see below

std::is_within_lifetime的示例应该算是一个完善,在老的版本中可以用一些技巧来实现类似这个判断的功能,但实现方式让开发者不爽,使用新近个接口就方便多了。

四、总结

标准里除了有让开发者感兴趣的比较重量级的实现,当然更多的还是一些细节的完善和改进。虽然说C++26是继C++11后的又一个重大的版本迭代,但仍然还是要对一些细节引起重视。抓大放小,也不是说把小的扔了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值