c++ - Some doubts about operator new() and handles in msvc?
淡淡烟草味
淡淡烟草味 2017-05-16 13:30:35
0
1
798
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

淡淡烟草味
淡淡烟草味

reply all(1)
阿神

_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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!