<new> 函数

get_new_handler

new_handler get_new_handler() noexcept;

备注

返回当前 new_handler

launder

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

提供一个对象,作为 newdeletenothrow 版本的自变量。

extern const std::nothrow_t nothrow;

备注

该对象用作与参数类型 std::nothrow_t 匹配的函数自变量。

示例

有关如何将 std::nothrow_t 用作函数参数的示例,请参阅 operator newoperator new[]

set_new_handler

安装一个用户函数,当 operator 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