运算符新功能

当一个语句例如以下程序时遇到,它转换为调用的函数 operator new:

备注

char *pch = new char[BUFFER_SIZE];

如果该请求针对零字节存储, new 运算符 返回指向不同的对象 (即重复调用 new 运算符 返回不同的指针)。 如果具有分配请求没有足够的内存, new 运算符 返回 NULL 或引发异常 (请参见 新建和删除运算符 有关更多信息)。

您可以编写尝试释放内存和重试分配的实例;请参见 _set_new_handler 有关更多信息。 有关更多详细信息在还原模式,请参见以下主题, 处理内存不足情况

operator new 功能的两个范围下表中描述。

运算符新功能的范围

运算符

范围

:: new 运算符

Global

类名称:: new 运算符

new 运算符 的第一个参数必须是类型 size_t (在 STDDEF.H) 定义的类型和返回类型总是 void *

全局 new 运算符 函数调用,当 运算符来分配固定类型对象时,不包含用户定义的 new 运算符 函数,并对任何类型类类型的对象。 当 运算符在分配时类的对象类型 new 运算符 定义的位置,该类的 new 运算符 调用。

为类定义的,因此, new 运算符 函数不能是虚拟的) 承载的静态成员函数 (隐藏该类类型对象的全局 new 运算符 功能。 考虑 用于分配和设置内存为特定值的情况:

// spec1_the_operator_new_function1.cpp
#include <malloc.h>
#include <memory.h>

class Blanks
{
public:
    Blanks(){}
    void *operator new( size_t stAllocateBlock, char chInit );
};
void *Blanks::operator new( size_t stAllocateBlock, char chInit )
{
    void *pvTemp = malloc( stAllocateBlock );
    if( pvTemp != 0 )
        memset( pvTemp, chInit, stAllocateBlock );
    return pvTemp;
}
// For discrete objects of type Blanks, the global operator new function
// is hidden. Therefore, the following code allocates an object of type
// Blanks and initializes it to 0xa5
int main()
{
   Blanks *a5 = new(0xa5) Blanks;
   return a5 != 0;
}

实参提供括号内。 传递给 Blanks::operator new 作为 chInit 参数。 但是,全局 new 运算符 函数被隐藏,导致如下代码生成错误:

Blanks *SomeBlanks = new Blanks;

在 Visual C++ 5.0 和早期版本中, nonclass 类型和所有排列 (无论它们是否 类型) 发布使用 运算符一直使用全局 new 运算符 功能。

从 Visual C++ 5.0 开始,编译器支持成员数组 和类声明的 删除 运算符。 例如:

// spec1_the_operator_new_function2.cpp
class MyClass
{
public:
   void * operator new[] (size_t)
   {
      return 0;
   }
   void   operator delete[] (void*)
   {
   }
};

int main() 
{
   MyClass *pMyClass = new MyClass[5];
   delete [] pMyClass;
}

请参见

参考

运算符删除功能

新运算符(C++)

删除运算符(C++)