我有一个类型为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 *)
根据我的理解,放置new运算符是由C ++实现提供的(或者可能是<new>
,我也尝试过#include
ing?)并简单地返回它的参数(new
使内存可用,而placement new是程序员说的给定内存是可用的)。
奇怪的是,当上面定义的(普通!)新运算符不在类中时,不会发生错误。事实上,没有定义它们的MyOtherType
工作得很好。
问题:发生了什么事?我该如何解决?
由于您已在类中定义了operator new
,因此需要使用全局new
来使用它的放置版本。
#include <new>
...
::new (reinterpret_cast<MyType*>(ptr)) MyType(*this);