奇怪的'new'构造函数
Strange 'new' constructor
我在检查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);
据我所知,这似乎不是一个类型转换。这个结构是什么意思?
这是placement new
。它只是调用一个带地址的构造函数。因此,在n
位置将构造一个T
类型的对象。
相关文章:
- 运算符 new 的执行顺序和构造函数的参数
- 使用复制构造函数初始化 new[]
- 在执行new期间是否可以在构造函数中传递不同的参数?
- 双指针在使用 new 时不调用对象构造函数
- 在 new 关键字中,由默认构造函数初始化的类中的元素是否也使用 new 关键字在C++?
- 使用 "new" 命令在 C++ 中的类构造函数中分配 2D 数组
- new[] / delete[] 并在C++中抛出构造函数/析构函数
- 构造函数不会将使用 new 初始化的数组作为参数
- "new"运算符是否总是调用构造函数?
- 重载运算符 new(),为什么构造函数被调用两次?
- 我应该使用<Object> shared_ptr myObject = (shared_ptr) <Object>new Object() 来访问私有构造函数吗?
- 如何安全地将 new 创建的对象传递到构造函数中
- 如果所述结构具有构造函数,则带有 new[] 的结构数组似乎不起作用
- C++构造函数中的'new auto'
- 构造函数中的 Malloc 在通过 New 调用时返回 NULL
- 访问std :: MAP中的静态构造函数New New拨号
- 尝试在没有new的情况下使用我的自定义类构造函数
- 为什么智能指针不能在其构造函数中为我调用 new()?
- 使用C++中的new()作为构造函数
- 如何在创建新的 obj() 时调用基类构造函数 new base(argT argV)