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)
参数 (Parameters)
size - 它包含所请求内存块的大小(以字节为单位)。
nothrow_value - 它包含常量nothrow_value 。
ptr - 它是指向已经分配的适当大小的内存块的指针。
返回值 (Return Value)
它返回指向新分配的存储空间的指针。
异常 (Exceptions)
如果它无法分配存储,那么它会抛出bad_alloc。
数据竞争 (Data races)
它修改返回值引用的存储。
例子 (Example)
在下面的例子解释了新的运算符。
#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]