放置新的超负荷普通新操作员

Placement new With Overloaded Ordinary new Operator

本文关键字:操作员 超负荷      更新时间:2023-10-16

我有一个类型为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*)’

国际商会告诉我:

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

据我所知,placement-new操作符是由C++实现提供的(或者可能是由<new>提供的,我也尝试过#includeing?(,并简单地返回其参数(new使内存可用,而placement-nnew是程序员说给定内存可用(。

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

问题:怎么回事?我该怎么修?

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

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