- C 标准库
 - C 标准库
 
- C++ 标准库
 - C++ 库 - 主页
 - C++ 库 - <fstream>
 - C++ 库 - <iomanip>
 - C++ 库 - <ios>
 - C++ 库 - <iosfwd>
 - C++ 库 - <iostream>
 - C++ 库 - <istream>
 - C++ 库 - <ostream>
 - C++ 库 - <sstream>
 - C++ 库 - <streambuf>
 - C++ 库 - <原子>
 - C++ 库 - <复杂>
 - C++ 库 - <异常>
 - C++ 库 - <功能>
 - C++ 库 - <限制>
 - C++ 库 - <语言环境>
 - C++ 库 - <内存>
 - C++ 库 - <新>
 - C++ 库 - <数字>
 - C++ 库 - <正则表达式>
 - C++ 库 - <stdexcept>
 - C++ 库 - <字符串>
 - C++ 库 - <线程>
 - C++ 库 - <元组>
 - C++ 库 - <类型信息>
 - C++ 库 - <实用程序>
 - C++ 库 - <valarray>
 
C++ 新库 - 运算符 new
描述
它分配 size 字节的存储空间,适当对齐以表示该大小的任何对象,并返回指向该块的第一个字节的非空指针。
宣言
以下是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 - 它包含常量 nothro。
ptr - 它是指向已分配的适当大小的内存块的指针。
返回值
它返回一个指向新分配的存储空间的指针。
例外情况
如果分配存储失败,则会抛出 bad_alloc。
数据竞赛
它修改返回值引用的存储。
例子
在下面的示例中解释了 new 运算符。
#include <iostream>
#include <new>
struct MyClass {
   int data[100];
   MyClass() {std::cout << "It constructed [" << this << "]\n";}
};
int main () {
   std::cout << "1: ";
   MyClass * p1 = new MyClass;
   std::cout << "2: ";
   MyClass * p2 = new (std::nothrow) MyClass;
   std::cout << "3: ";
   new (p2) MyClass;
   std::cout << "4: ";
   MyClass * p3 = (MyClass*) ::operator new (sizeof(MyClass));
   delete p1;
   delete p2;
   delete p3;
   return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 -
1: It constructed [0x21f9ba0] 2: It constructed [0x21f9d40] 3: It constructed [0x21f9d40]
新的.htm