Why does not std::nothrow work as expected in gcc(4.9)?

后端 未结 1 1421
北恋
北恋 2021-01-21 17:24

I\'ve seen lots of people in my team checking null pointers like this:

    SomeClass *pSc = new SomeClass;
    if ( NULL == pSc )
    {
        // cope with erro         


        
相关标签:
1条回答
  • 2021-01-21 17:52

    Believe or not, this is standard compliant behavior:

    5.3.4/7

    The expression in a noptr-new-declarator is erroneous if:
    [...] — its value is such that the size of the allocated object would exceed the implementation-defined limit (annex B); or
    [...]

    If the expression, after converting to std::size_t, is a core constant expression and the expression is erroneous, the program is ill-formed. Otherwise, a new-expression with an erroneous expression does not call an allocation function and terminates by throwing an exception of a type that would match a handler (15.3) of type std::bad_array_new_length (18.6.2.2). When the value of the expression is zero, the allocation function is called to allocate an array with no elements.

    In short, non-throwing allocator function is not even called, exception is thrown by new-expression itself.

    I assume that you are not using modern C++ version, because in those std::numeric_limits<long long>::max() marked as constexpr and is a core constant expression, which yields compile-time error.

    Clang, probably has implementation-defined limit set higher than max value of long lond, bypassing this quirk of C++.

    0 讨论(0)
提交回复
热议问题