C++ New::operator new[]



C++ New::operator new[] 返回一个指向第一个元素的指针,该指针在分配和初始化对象数组后。相反,new 运算符的行为相同,但仅允许单个分配而不是数组。使用 new 和 delete 以及 new[] 和 delete[] 进行释放和对象删除。

尽管 operator new[] 可以像 C++ 中的任何其他函数一样显式调用,但它具有特定的行为。如果表达式对数组类型使用 new 运算符,它首先使用数组类型说明符的大小作为第一个参数调用函数 operator new。如果成功,则会自动初始化或构建数组中的每个对象。

语法

以下是 C++ New::operator new[] 的语法:

void* operator new[] (std::size_t size) throw (std::bad_alloc); (throwing allocation) void* operator new[] (std::size_t size, const std::nothrow_t& nothrow_value) throw(); (nothrow allocation) void* operator new[] (std::size_t size, void* ptr) throw(); (placement)

参数

  • size - 包含请求的内存块的大小(以字节为单位)。
  • nothrow_value - 包含常量 nothrow。
  • ptr - 指向已分配的适当大小的内存块的指针。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例 1

让我们看看下面的示例,我们将使用 operator new[] 并检索输出。

Open Compiler
#include <cstdio> #include <cstdlib> #include <new> void* operator new[](std::size_t sz) { std::printf(" operator new[](size_t), size = %zu\n", sz); if (sz == 1) ++sz; if (void *ptr = std::malloc(sz)) return ptr; throw std::bad_alloc{}; } int main() { int* p2 = new int[12]; delete[] p2; }

输出

让我们编译并运行上面的程序,这将产生以下结果:

operator new[](size_t), size = 48

示例 2

让我们看看另一种情况,我们将使用 operator new[] 以及特定的分配。

Open Compiler
#include <iostream> struct A { static void* operator new(std::size_t count) { std::cout << "custom operator new for size " << count << '\n'; return ::operator new(count); } static void* operator new[](std::size_t count) { std::cout << "custom operator new[] for size " << count << '\n'; return ::operator new[](count); } }; int main() { A* p1 = new A; delete p1; A* p2 = new A[13]; delete[] p2; }

输出

运行上述代码后,它将显示如下输出:

custom operator new for size 1
custom operator new[] for size 13

示例 3

考虑以下情况,我们将检查 operator new[] 的功能。

Open Compiler
#include <iostream> #include <new> struct MyClass { int data; MyClass() { std::cout << '@'; } }; int main () { std::cout << "constructions (1): "; MyClass * p1 = new MyClass[10]; std::cout << '\n'; std::cout << "constructions (2): "; MyClass * p2 = new (std::nothrow) MyClass[5]; std::cout << '\n'; delete[] p2; delete[] p1; return 0; }

输出

当代码执行时,它将生成如下输出:

constructions (1): @@@@@@@@@@
constructions (2): @@@@@
广告