【问题标题】:Strange 'new' constructor奇怪的“新”构造函数
【发布时间】:2013-05-10 11:07:46
【问题描述】:

我在检查 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);

据我了解,它似乎不是类型转换。这个结构是什么意思?

【问题讨论】:

    标签: c++ qt


    【解决方案1】:

    这是placement new。它只是调用带有地址的构造函数。因此,T 类型的对象将在位置n 处构造。它看起来也是一个调用复制构造函数的放置 new。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-02
      相关资源
      最近更新 更多