What does ::new mean?

本秂侑毒 提交于 2019-12-01 02:24:22

问题


When examining the MS directX 11 DXUT example, the following code appeared:

template<typename TYPE> HRESULT CGrowableArray <TYPE>::SetSize( int nNewMaxSize )
{
int nOldSize = m_nSize;

if( nOldSize > nNewMaxSize )
{
    assert( m_pData );
    if( m_pData )
    {
        // Removing elements. Call dtor.

        for( int i = nNewMaxSize; i < nOldSize; ++i )
            m_pData[i].~TYPE();
    }
}

// Adjust buffer.  Note that there's no need to check for error
// since if it happens, nOldSize == nNewMaxSize will be true.)
HRESULT hr = SetSizeInternal( nNewMaxSize );

if( nOldSize < nNewMaxSize )
{
    assert( m_pData );
    if( m_pData )
    {
        // Adding elements. Call ctor.

        for( int i = nOldSize; i < nNewMaxSize; ++i )
            ::new ( &m_pData[i] ) TYPE;
    }
}

return hr;
}

This can be found in DXUTmisc.h on line 428 on my version of DXSDK (June2010). I'm wondering about that ::new thing....I'm trying to Google and search on stack overflow but seems the searching engine is discarding the two colons when I type "::new" in the search bar....


回答1:


The ::new call means that the program is trying to use the global new operator to allocate space, rather than using any new operator that was defined at class or namespace scope. In particular, this code is trying to use something called placement new in which the object being created is placed at a specific location in memory. By explicitly calling back up into the global scope, the function ensures that this correctly uses placement new and doesn't accidentally call a different allocation function introduced somewhere in the scope chain.

Hope this helps!




回答2:


::new ensures the new operator at global, i.e. standard new operator, is called. Note :: before new indicates global scope.



来源:https://stackoverflow.com/questions/14147029/what-does-new-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!