new_nothrow

new_nothrow (std::nothrow_t / std::nothrow)

<new> 헤더에 정의되어 있어요. 던지는(throw) 할당 함수와 던지지 않는(non-throwing) 할당 함수의 오버로드를 구분하는 데 쓰는 빈 클래스 타입과 그 상수예요.

출처: cppreference

본문

struct nothrow_t {};                        // (1) until C++11
struct nothrow_t { explicit nothrow_t() = default; };   // (1) since 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 오버로드: 실패 시 bad_alloc
        }
    }
    catch (const std::bad_alloc& e)
    {
        std::cout << e.what() << '\n';
    }

    // nothrow 오버로드: 실패 시 예외 대신 널 반환
    if (int* p = new (std::nothrow) int[100000000ul])
    {
        delete[] p;
    } else {
        std::cout << "throw 대신 nullptr\n";
    }
}

new (std::nothrow) T처럼 쓰면 메모리 할당 실패 시 예외를 던지는 대신 널 포인터를 돌려줘요. 예외 처리보다 오류를 직접 확인하고 싶을 때 유용해요.

더 알아보기 (Learn more)

cppreference