Namespaces
Variants

std:: nothrow

From cppreference.net
< cpp ‎ | memory ‎ | new
Utilities library
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
Определено в заголовочном файле <new>
(1)
struct nothrow_t { } ;
(до C++11)
struct nothrow_t { explicit nothrow_t ( ) = default ; } ;
(начиная с C++11)
extern const std:: nothrow_t nothrow ;
(2)

std::nothrow_t — это пустой класс, используемый для разрешения неоднозначности перегрузок выбрасывающих и не выбрасывающих исключения функций выделения памяти . std::nothrow является константой этого типа.

Пример

#include <iostream>
#include <new>
int main()
{
    try
    {
        while (true)
        {
            new int[100000000ul];   // throwing overload
        }
    }
    catch (const std::bad_alloc& e)
    {
        std::cout << e.what() << '\n';
    }
    while (true)
    {
        int* p = new(std::nothrow) int[100000000ul]; // non-throwing overload
        if (p == nullptr)
        {
            std::cout << "Allocation returned nullptr\n";
            break;
        }
    }
}

Вывод:

std::bad_alloc
Allocation returned nullptr

Отчеты о дефектах

Следующие отчеты об изменениях поведения, влияющие на дефекты, были применены ретроактивно к ранее опубликованным стандартам C++.

DR Применяется к Поведение в опубликованной версии Корректное поведение
LWG 2510 C++11 конструктор по умолчанию был неявным, что могло приводить к неоднозначности сделан явным

Смотрите также

функции выделения памяти
(функция)