2013-05-15 74 views
0

我遇到了下面的代碼,而檢查的Qt來源:奇怪的「新」的構造

template <typename T> 
Q_INLINE_TEMPLATE void QList<T>::node_construct(Node *n, const T &t) 
{ 
    if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) n->v = new T(t); 
    else if (QTypeInfo<T>::isComplex) new (n) T(t); 
#if (defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__IBMCPP__)) && !defined(__OPTIMIZE__) 
    // This violates pointer aliasing rules, but it is known to be safe (and silent) 
    // in unoptimized GCC builds (-fno-strict-aliasing). The other compilers which 
    // set the same define are assumed to be safe. 
    else *reinterpret_cast<T*>(n) = t; 
#else 
    // This is always safe, but penaltizes unoptimized builds a lot. 
    else ::memcpy(n, static_cast<const void *>(&t), sizeof(T)); 
#endif 
} 

它有一個奇怪的new指令:

new (n) T(t); 

據我瞭解,這似乎不是一個類型轉換。這種結構意味着什麼?

回答

7

這是placement new。它只是調用一個地址的構造函數。因此,類型T的對象將在位置n構建。它也看起來是一個新的調用複製構造函數的佈局。

+1

請問谷歌furhter :)謝謝! –