11

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....

Lycoress
  • 113
  • 1
  • 7
  • 1
    `::` is the [scope resolution operator](http://en.wikipedia.org/wiki/Scope_resolution_operator) and by itself it specifies the global scope. It makes sure that `new` is called from the global scope. – Joe Jan 03 '13 at 20:51

2 Answers2

19

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!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • +1 for pointing out the XY question. (They asked X, but really needed to know Y) – Yakk - Adam Nevraumont Jan 03 '13 at 20:54
  • +1 for point out the placement new. I should have noticed this. – xis Jan 03 '13 at 20:59
  • Thanks, I think its mainly an issue with the placement new. The actual memory allocation is done on the line of **SetSizeInternal()** with a realloc call. So the new here is really just to call **TYPE**'s constructor, if any. – Lycoress Jan 03 '13 at 21:13
  • And what does TYPE mean? (i.e `::new (&x) int`) what does the int do? – David G Jan 03 '13 at 21:52
  • @David- Here, `TYPE` is a template parameter indicating what type of objects are being stored. The line `::new (&x) int` means "construct an object of type `int` at the memory location referred to by the pointer `&x`. – templatetypedef Jan 03 '13 at 21:53
3

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

xis
  • 24,330
  • 9
  • 43
  • 59