首页 > 编程语言 >C++23特性一览

C++23特性一览

时间:2024-07-02 14:57:59浏览次数:3  
标签:std 23 int 一览 C++ New include

在这里插入图片描述

New language features

New language feature testing macros

Explicit object parameters, explicit object member functions (deducing this)

if consteval / if not consteval

Multidimensional subscript operator (e.g. v[1, 3, 7] = 42;)

static operator()

static operator[]

auto(x): decay-copy in the language

Attributes on lambda-expressions

Optional extended floating-point types: std::float{16|32|64|128}_t, and std::bfloat16_t.

#elifdef, #elifndef, and #warning

Literal suffix ‘Z’/‘z’ for (signed) std::size_t literals

Assumptions via new attribute [[assume(expression)]]

Named universal character escapes

A portable source file encoding is UTF-8

White-spaces trimming before line splicing.

New library features

New modules

std and std.compat

New headers

C compatibility headers:

Library features

New library feature testing macros

New ranges fold algorithms

String formatting improvements

“flat” container adaptors: std::flat_map, std::flat_multimap, std::flat_set, std::flat_multiset

std::mdspan

std::generator

std::basic_string::contains, std::basic_string_view::contains

Construction of std::string_view from nullptr is disallowed

std::basic_string::resize_and_overwrite

Monadic operations for std::optional: or_else, and_then, transform

Stacktrace library

New ranges algorithms:

New range adaptors (views):

Changes to ranges library

Changes to views library

Marking unreachable code: std::unreachable

New vocabulary type std::expected

std::move_only_function

New I/O stream std::spanstream with program-provided fixed size buffer

std::byteswap

std::to_underlying

Associative containers heterogeneous erasure.


C++23, the latest iteration of the C++ programming language standard, follows its predecessor C++20 with several enhancements aimed at improving usability, performance, and code clarity. As a refinement of the language, C++23 doesn’t introduce as many large features as C++20, which included major additions like concepts, ranges, and coroutines. However, it does provide important updates and new features that developers should be aware of. This article delves into some of the most significant changes and improvements in C++23 compared to previous versions.

  1. Simplified Syntax for using Declarations
    C++23 has introduced a simplified syntax for using declarations, which allows a base class’s constructor or assignment operator to be inherited more concisely. Previously, inheriting constructors from a base class required specifying each constructor individually, which could be verbose and error-prone. The new feature reduces boilerplate code and enhances readability.
struct Base {
    Base(int x) {}
    Base(double x, int y) {}
};

struct Derived : Base {
    using Base::Base;  // Inherit all constructors from Base
};
  1. Standardized std::print
    One of the most anticipated features in C++23 is the introduction of std::print. This feature aims to standardize a common operation—printing to the console—which previously required using std::cout or other more complex I/O functions. std::print simplifies this task by providing a straightforward way to print formatted data, reducing the learning curve for new C++ programmers and increasing code clarity.
#include <iostream>

int main() {
    std::print("Hello, World!\n");
    std::print("The answer is: {}\n", 42);
}
  1. Enhancements to std::expected
    std::expected is a template class that handles expected errors as an alternative to exceptions. It was proposed to provide a way to return and check for error conditions in a manner that is more visible in the function signature than exceptions. C++23 aims to include this feature to simplify error handling and improve performance by avoiding the overhead associated with exceptions.
#include <expected>
#include <iostream>

std::expected<int, const char*> compute(int x) {
    if (x < 0) return "Negative input not allowed";
    return x * x;
}

int main() {
    auto result = compute(10);
    if (result) {
        std::cout << "Result: " << *result << std::endl;
    } else {
        std::cout << "Error: " << result.error() << std::endl;
    }
}
  1. std::mdspan
    Another notable addition is std::mdspan a multidimensional array view that provides an interface for accessing elements in a multidimensional data layout without owning the underlying data. This feature is crucial for scientific and numerical applications where performance and flexibility in data access patterns are important.
#include <mdspan>
#include <vector>
#include <iostream>

int main() {
    std::vector<int> data = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    std::mdspan<int, std::extents<3, 3>> matrix(data.data());

    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            std::cout << matrix(i, j) << " ";
        }
        std::cout << "\n";
    }
}
  1. Improved Lambda Expressions
    C++23 continues to enhance lambda expressions by introducing new features such as simplified syntax for not capturing any variables and improved constexpr capabilities. These improvements make lambdas more powerful and easier to use in a wider range of contexts, including compile-time programming.
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    auto is_even = [](int x) constexpr { return x % 2 == 0; };
    auto pos = std::find_if(numbers.begin(), numbers.end(), is_even);

    if (pos != numbers.end()) {
        std::cout << "First even number: " << *pos << std::endl;
    }
}
  1. constexpr Enhancements
    The constexpr specifier has been significantly expanded in C++23, allowing more complex computations to be performed at compile time. This includes the ability to use dynamic memory allocation, try and catch blocks, and virtual calls within constexpr functions, which were previously not possible.
#include <iostream>

constexpr int* create_array(int size) {
    return new int[size]{1, 2, 3};  // Dynamic allocation in constexpr
}

int main() {
    constexpr auto* array = create_array(3);
    std::cout << array[0] << ", " << array[1] << ", " << array[2] << std::endl;
    delete[] array;
}
  1. Networking TS (Technical Specification)
    While not fully integrated into the standard, progress has been made on the Networking TS, which is expected to eventually be part of the standard library. C++23 has made strides towards incorporating more networking capabilities directly into the standard library, facilitating easier and more standardized network programming.
    Conclusion
    C++23 offers several practical enhancements that refine the capabilities introduced in C++20 and earlier versions. As with any new standard, the adoption rate will depend on compiler support and the specific needs of projects. Nonetheless, personally I find these improvements in C++23 an attractive upgrade for C++ developers seeking to leverage the latest advancements in the language.

标签:std,23,int,一览,C++,New,include
From: https://blog.csdn.net/lianshaohua/article/details/140126091

相关文章

  • C++编译问题,解决arm下链接静态库,引起的relocation R_AARCH64_ADR_PREL_PG_HI21 agains
    显示的完整错误如下:relocationR_AARCH64_ADR_PREL_PG_HI21againstsymbol`ZN2c43yml9free_implEPvmS1'whichmaybindexternallycannotbeusedwhenmakingasharedobject;recompilewith-fPIC根据提示,在链接.a静态库时,应该在编译时加上参数-fPIC然而CMake文件中已......
  • 2023-2025年最值得选择的Java毕业设计选题大全:1000个热门选题推荐✅✅✅
    ......
  • 详解C++中的容器,其特点与常用方法
    1.容器的定义在C++中,容器的概念是指一种对象类型,它可以持有其他对象或指向其他对象的指针。这种对象类型在数据存储上提供了一种有效的方式来管理一组元素。容器在C++中通常是模板类的形式。一般来说,容器内的元素都是相同类型的。即如果该容器内存放的是int类型的数据,那么......
  • QOJ2376 Game on a Tree (树形 dp)
    QOJ2376GameonaTree树形dp因为题目限制对于两个人等价,所以朴素的,考虑将\(u\)与祖先和后代连边,构成一个新的无向图。那么题目就变成:在无向图中选一点,每一次操作就是走一步到新的点,谁先不能走,那么另一个人获胜。先说结论:当无向图有完美匹配时,后手胜,反之先手胜。证明:若有......
  • C++个人学习笔记,Typora编写
    第1章:杂叙1.名字空间namespacexxx在main函数中划分变量空间时,需要指定“xxx::a=1”2.倘若需要使用cin和cout,需要在main函数外使用usingstd::cin;或者从usingstd::cout;标准库中的名字都属于标准名字空间std3.变量存在的意义时为了方便管理内存空间4.程序块内定义内部变......
  • Qt/C++开发经验小技巧296-300
    使用QDir::setCurrent设置当前目录后,会影响程序中的所有相对目录的执行,导致可能的意外发生,一般相对目录都默认是可执行文件所在目录,所以如果程序中为了特殊处理临时调用了QDir::setCurrent设置过相对目录,建议处理完成以后立即切换回来。QDir::setCurrent("f:/");QImageimg(":......
  • C++:类与面向对象&static和this关键字&其他关键字
    类与面向对象struct和class(1)struct是C中用户自定义类型,主要功能是对功能相关数据的封装(2)struct不能直接封装函数,但可以通过封装函数指针来间接封装函数(3)struct就是class的初级阶段,class在struct基础上做了很多扩展,便有了面向对象访问权限(1)类是对数据(成员变......
  • 深入理解 C++11 多线程编程:从入门到实践
    C++多线程编程是指使用C++提供的多线程库来并行执行代码块,从而提高程序的性能和响应能力。C++11标准引入了多线程支持,使得在C++中进行多线程编程变得更加容易和直观。以下是C++多线程编程的基本知识,并附有例子代码。多线程的基本概念线程(Thread):线程是进程中的一个执......
  • C/C++ 赋值表达式注意事项
    在C/C++中,赋值表达式是基础且关键的一部分,它用于给变量赋值。理解和正确使用赋值表达式对于编写有效、可维护的代码至关重要。以下是一些关于C/C++赋值表达式的注意事项:赋值操作符:在C/C++中,赋值是通过赋值操作符=完成的。这意味着将右侧的值或表达式的结果赋给左侧的变......
  • 2024年6.23-6.26学习总结
    2024年6.23--6.26学习总结考试24号考计算机网络,26号考形式语言与自动机。这几天基本都在复习。形式语言与自动机dfa极小化1.先删去不可达状态和陷阱态。2.假如状态有q1,q2,q3,q4,q5,q6,q7,q8,先将所有终止状态取出分为一组比如{q6,q8},然后在另一组中找到无法区分的状态(到终止......