Placement new With Overloaded Ordinary new 运算符

Placement new With Overloaded Ordinary new Operator

我有一个 MyType 类型的对象,出于 SSE 的原因,它需要 16 字节对齐。因此,我编写了一个分配器并重载了 new 运算符。 MyType 中的方法:

inline static void* operator new(size_t size) {
    awesome::my_allocator<MyType,16> alloc;
    return alloc.allocate(size);
}
inline static void* operator new[](size_t size) { return operator new(size); }
inline static void operator delete(void* ptr) {
    awesome::my_allocator<MyType,16> alloc;
    alloc.deallocate(reinterpret_cast<MyType*>(ptr),0); //last arg ignored in my impl
}
inline static void operator delete[](void* ptr) { operator delete(ptr); }

现在,出于缓存局部性的原因,我需要将一个实例复制构造到一块特定的 64 字节对齐内存中:

void MyType::copy_into(uint8_t* ptr) const {
    new (reinterpret_cast<MyType*>(ptr)) MyType(*this);
}

GCC 告诉我:

error: no matching function for call to ‘MyType::operator new(sizetype, MyType*)’

ICC 告诉我:

error : function "MyType::operator new" cannot be called with the given argument list
1>              argument types are: (unsigned __int64, MyType *)

据我了解,放置新运算符是由 C++ 实现提供的(或者可能是由 <new> 提供的,我也尝试过 #includeing?)并且只是 returns 它的论点(new 使内存 可用 ,而 placement new 是程序员说给定的内存可用)。

奇怪的是,当上面定义的(普通!)新运算符在 [=42= 中 not ].事实上,MyOtherType,它没有定义它们,工作得很好。

问:怎么回事?我该如何解决?

由于您在 class 中定义了 operator new,因此您需要使用全局 new 来使用它的放置版本。

#include <new>

...

::new (reinterpret_cast<MyType*>(ptr)) MyType(*this);