使用重载的普通新运算符放置新的

ima*_*ett 12 c++ 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); }
Run Code Online (Sandbox Code Playgroud)

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

void MyType::copy_into(uint8_t* ptr) const {
    new (reinterpret_cast<MyType*>(ptr)) MyType(*this);
}
Run Code Online (Sandbox Code Playgroud)

GCC告诉我:

error: no matching function for call to ‘MyType::operator new(sizetype, MyType*)’
Run Code Online (Sandbox Code Playgroud)

ICC告诉我:

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

根据我的理解,放置new运算符由C++实现提供(或者可能由<new>我也尝试过#include?)并简单地返回其参数(new使内存可用,并且placement new是程序员说给定的内存可用).

奇怪的是,当上面定义的(普通!)新运算符不在类中时,不会发生错误.实际上,没有定义它们,工作得很好.MyOtherType

问题:发生了什么事?我该如何解决?

R S*_*ahu 9

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

#include <new>

...

::new (reinterpret_cast<MyType*>(ptr)) MyType(*this);
Run Code Online (Sandbox Code Playgroud)