目录

operator new[]

描述 (Description)

它为数组分配存储空间。

声明 (Declaration)

以下是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)

C++11

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

参数 (Parameters)

  • size - 它包含所请求内存块的大小(以字节为单位)。

  • nothrow_value - 它包含常量nothrow_value

  • ptr - 它是指向已经分配的适当大小的内存块的指针。

返回值 (Return Value)

它返回指向新分配的存储空间的指针。

异常 (Exceptions)

如果它无法分配存储,那么它会抛出bad_alloc。

数据竞争 (Data races)

它修改返回值引用的存储。

例子 (Example)

在下面的例子解释了新的运算符。

#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): @@@@@
↑回到顶部↑
WIKI教程 @2018