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
    }
}
相关推荐
ShineWinsu2 天前
对于 C++:C++20中Concept(概念) 与 Coroutine(协程)的解析
linux·开发语言·网络·c++·c++20·epoll
Lzg_na9 天前
C++20 Concept 核心概念、语法详解与三大工程实践场景
c++20
Billy121389 天前
Day14-C++20 Modules:模块声明与导入、模块分区、与头文件对比、迁移策略
c++20·c++进阶学习
程序猿编码9 天前
不用GPU,不用多线程,我用C++20手写了一个Gemma 3推理引擎
pytorch·语言模型·大模型·c++20·推荐算法
Billy1213811 天前
Day15-C++20 三路比较运算符 `<=>`:一次定义,全面排序
c++20·c++进阶学习
A_cainiao_A18 天前
C++20:std::stop_source让线程说停就听
开发语言·c++20
小小龙学IT22 天前
C++20 Ranges 库实现原理深度解析:从视图适配器到管道运算符
c++20
Billy1213825 天前
C++20 Concepts:约束与概念的现代范式
c++20·c++进阶学习
可爱系程序猿1 个月前
mfc90.dll 缺失如何处理?VC++ 2008 运行库与并行程序集排查记录
程序人生·电脑·c++20
code_pgf1 个月前
C++11 / C++14 / C++17 / C++20 新特性总结
c++·c++20