8

检查 MS directX 11 DXUT 示例时,出现以下代码:

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;
}

这可以在我的 DXSDK 版本(2010 年 6 月)的第 428 行的 DXUTmisc.h 中找到。我想知道::new的事情....我正在尝试谷歌并搜索堆栈溢出,但是当我在搜索栏中键入“::new”时,搜索引擎似乎正在丢弃两个冒号... .

4

2 回答 2

18

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!

于 2013-01-03T20:54:03.327 回答
3

::new 确保调用全局的 new 运算符,即标准的 new 运算符。注意:: 之前的 new 表示全局范围。

于 2013-01-03T20:53:22.410 回答