你知道吗?在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
}
}