共用方式為


operator new (<new>)

new-expression 配置個別物件存放區時呼叫的函式。

void* operator new(
   std::size_t _Count
) throw(bad_alloc);
void* operator new(
   std::size_t _Count,        
   const std::nothrow_t&
) throw( );
void* operator new(
   std::size_t _Count, 
   void* _Ptr
) throw( );

參數

  • _Count
    要配置的存放區位元組數目。

  • _Ptr
    要傳回的指標。

傳回值

新配置儲存區之最低位元組位址的指標。 或 _Ptr.

備註

第一個函式是由新的運算式呼叫配置儲存區適當最好是對齊的 _Count 個位元組表示該大小的所有物件。 程式可以定義與取代 Standard C++ 程式庫中定義的預設版本與的這個函式簽章的替代函式,以便為可取代。

,只有在儲存體配置,可以依照要求必要的行為是傳回非 null 指標。 每一個這類組態產生指標儲存其他配置儲存區斷續文字範圍。 後續呼叫和存取配置儲存區順序是未指定的。 原本儲存的值是未指定的。 傳回的指標指向啟動 (最低的位元組位址) 配置的儲存區。 如果計數為零,則傳回的值不等於函式傳回的其他值。

預設行為是執行迴圈。 在這個迴圈內,函式會先嘗試配置要求的儲存區。 這個嘗試是否牽涉到 malloc(size_t) 的呼叫是未指定的。 如果嘗試成功,則函式會傳回指標所配置的儲存區。 否則,函式會以指定的 新的處理常式。。 如果呼叫的函式會傳回,迴圈重複。 這個迴圈會終止,當嘗試配置要求的儲存成功,或當被呼叫的函式無法傳回時。

新的處理常式必要行為是執行下列其中一項作業:

  • 進行配置的詳細儲存可用則傳回。

  • 呼叫 abortexit(int)。

  • 就會擲回型別 **bad_alloc.**物件

新的處理常式。 的預設行為會擲回型別 bad_alloc物件。 null 指標指定預設的新處理常式。

後續呼叫和存取配置儲存區順序會 operator new(size_t) 未指定的,與儲存的原始值。

第二個函式會將新的運算式呼叫配置儲存區適當最好是對齊的 _Count 個位元組表示該大小的所有物件。 程式可以定義與取代 Standard C++ 程式庫中定義的預設版本與的這個函式簽章的替代函式,以便為可取代。

預設行為是傳回 operator new(_Count),如果該函式成功。 否則,會傳回 null 指標。

第三個函式會將 new 運算式,表單會呼叫 new (長度) T。 在此例中, 引數 包含單一物件的指標。 這有助於建構物件在已知的電子郵件地址。 函式會傳回 _Ptr

operator new配置中未使用的記憶體區域,呼叫 delete 運算子

如需擲回的或 nonthrowing 行為的新資訊,請參閱 新增和刪除運算子

範例

// new_op_new.cpp
// compile with: /EHsc
#include<new>
#include<iostream>

using namespace std;

class MyClass 
{
public: 
   MyClass( )
   {
      cout << "Construction MyClass." << this << endl;
   };

   ~MyClass( )
   {
      imember = 0; cout << "Destructing MyClass." << this << endl;
   };
   int imember;
};

int main( ) 
{
   // The first form of new delete
   MyClass* fPtr = new MyClass;
   delete fPtr;

   // The second form of new delete
   MyClass* fPtr2 = new( nothrow ) MyClass;
   delete fPtr2;

   // The third form of new delete
   char x[sizeof( MyClass )];
   MyClass* fPtr3 = new( &x[0] ) MyClass;
   fPtr3 -> ~MyClass();
   cout << "The address of x[0] is : " << ( void* )&x[0] << endl;
}

範例輸出。

Construction MyClass.000B3F30
Destructing MyClass.000B3F30
Construction MyClass.000B3F30
Destructing MyClass.000B3F30
Construction MyClass.0023FC60
Destructing MyClass.0023FC60
The address of x[0] is : 0023FC60

需求

標題: <new>

命名空間: std

請參閱

參考

new operator (STL Samples)

nothrow_t Structure

operator delete (<new>)