<new> 函式

get_new_handler

new_handler get_new_handler() noexcept;

備註

傳回目前的 new_handler

清洗

template <class T>
    constexpr T* launder(T* ptr) noexcept;

參數

ptr
記憶體中位元組的位址,其保存類型類似于 T 的物件。

傳回值

指向 X 之 T* 類型的 值。

備註

也稱為指標優化屏障。

當其引數的值可用於常數運算式時,用作常數運算式。 如果位於另一個物件所佔用的儲存體內,可透過指向物件的指標值來存取儲存體位元組,而該物件具有類似的指標。

範例

struct X { const int n; };

X *p = new X{3};
const int a = p->n;
new (p) X{5}; // p does not point to new object because X::n is const
const int b = p->n; // undefined behavior
const int c = std::launder(p)->n; // OK

nothrow

提供 物件,以做為 和 delete 版本的 new 引數 nothrow

extern const std::nothrow_t nothrow;

備註

此物件是用來作為函式引數,以符合參數類型 std::nothrow_t

範例

如需如何使用 std::nothrow_t 作為函式參數的範例,請參閱 operator newoperator new[]

set_new_handler

安裝使用者函式,這個函式會在運算子 new 嘗試配置記憶體時失敗時 呼叫。

new_handler set_new_handler(new_handler Pnew) throw();

參數

Pnew
new_handler要安裝的 。

傳回值

第一次呼叫時,會傳回 0,後續呼叫時,則傳回前一個 new_handler

備註

函式會 Pnew 儲存在它所維護的靜態 new 處理常式 指標中,然後傳回先前儲存在指標中的值。 處理常式 new 是由 operator new 使用。

範例

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

using namespace std;
void __cdecl newhandler( )
{
   cout << "The new_handler is called:" << endl;
   throw bad_alloc( );
   return;
}

int main( )
{
   set_new_handler (newhandler);
   try
   {
      while ( 1 )
      {
         new int[5000000];
         cout << "Allocating 5000000 ints." << endl;
      }
   }
   catch ( exception e )
   {
      cout << e.what( ) << endl;
   }
}
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
The new_handler is called:
bad allocation