C++20中带有约束条件的new

你知道吗?在C++20中,提出了约束与概念的新特性。

我们在 new 时可以对数据类型进行约束,这样我们可以在代码层面更加显示的表示出我们需要操作的类型。

复制代码
#include <concepts>
#include <iostream>

int main() {
    // 约束为一个整形
    auto q1 = new std::integral auto(1);
    // 约束为一个有符号整形
    auto q2 = new std::unsigned_integral auto(1ull);
    // 编译错误,1ull不是一个有符号的整形
    // auto q3 = new std::signed_integral auto(1ull);
}

禁止抛出异常

在 C 语言中使用 malloc 函数,若申请内存失败,则会返回空指针。但在 C++ 中的 new 则是直接抛出异常,若不想有异常,则可以在 new 时指定 std::nothrow。这样在申请失败时候就可以用是否为空来进行判断。

复制代码
#include <new>

int main() {
    int* q = new (std::nothrow) int;
    if (q != nullptr) {
        // success
    } else {
        // error
    }
}
相关推荐
十五年专注C++开发4 天前
全面深入了解C++20 范围库(std::ranges)
c++20·管道·哨兵·视图·ranges
小小龙学IT7 天前
C++20 协程深度解析:从原理到高性能异步框架实战
junit·c++20
楼田莉子11 天前
C++20新特性:协程
开发语言·c++·后端·学习·c++20
ouliten14 天前
C++笔记:C++20风格线程池
c++·笔记·c++20
眠りたいです15 天前
现代C++:C++17中的新库特性
开发语言·c++·c++20·c++17
楼田莉子22 天前
C++20新特性:Range库
开发语言·c++·后端·学习·c++20
楼田莉子23 天前
C++20现代特性:概念与约束
开发语言·c++·后端·学习·c++20
aluluka23 天前
C++ 20 协程的探索
c++·c++20
君鼎1 个月前
内存池完整实现——C++20版
c++20·内存池
普通网友1 个月前
记录我适配iOS26遇到的一些问题
c++20