Home  >  Q&A  >  body text

c++ - Some doubts about operator new() and handles in msvc?

void* __CRTDECL operator new(size_t const size)
{
    for (;;)
    {
        if (void* const block = malloc(size))
        {
            return block;
        }

        if (_callnewh(size) == 0)
        {
            if (size == SIZE_MAX)
            {
                __scrt_throw_std_bad_array_new_length();
            }
            else
            {
                __scrt_throw_std_bad_alloc();
            }
        }

        // The new handler was successful; try to allocate again...
    }
}

I know that this endless loop is to wait for the memory to be allocated successfully and then return the pointer. However, my operating system knowledge is very weak (non-major), so I would like to ask everyone about the endless loop here. How is the second if of analyzed (such as the processing of the handle here, etc.).

Thanks

淡淡烟草味淡淡烟草味2685 days ago783

reply all(1)I'll reply

  • 阿神

    阿神2017-05-16 13:32:35

    _callnewh will call a handle to handle memory allocation failure. This handle can try to release some memory or wait for a period of time or directly throw an exception?. If the handle call returns _callnewh(size) != 0,那么new会再一次尝试申请,如果调用失败_callnewh(size) == 0 successfully, the relevant exception is thrown.

    if (size == SIZE_MAX)说明申请的对象数太多(size_t理论上能表达任何对象的数量)。elseIt is a general application failure. std_bad_array_new_length and std_bad_alloc refer to the corresponding exceptions in the standard library.

    Related interface: _set_new_handler

    reply
    0
  • Cancelreply