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

问题描述 投票:12回答:1

我有一个类型为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>,我也尝试过#includeing?)并简单地返回它的参数(new使内存可用,而placement new是程序员说的给定内存是可用的)。

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

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

c++ new-operator
1个回答
9
投票

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

#include <new>

...

::new (reinterpret_cast<MyType*>(ptr)) MyType(*this);
© www.soinside.com 2019 - 2024. All rights reserved.