【发布时间】:2015-10-07 18:23:39
【问题描述】:
我有一个 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 *)
据我了解,placement new 运算符由 C++ 实现提供(或者可能由<new>,我也尝试过#includeing?)并简单地返回它的参数(new 使内存 available,placement new 是程序员说给定的内存可用)。
奇怪的是,当上面定义的(普通!)新运算符在类中 not 时,会发生错误 not。事实上,MyOtherType 没有定义它们,但工作得很好。
问题:发生了什么事?我该如何解决?
【问题讨论】:
-
也许重载 new 以获取 2 个参数 - operator new(size, align) - 这样正常的 1 个参数新闻不会受到影响。这可能会通过让编译器使用内置类型来绕过编译器抱怨。 throw 与 nothrow 重载也可能导致一些问题。
-
所有这些都发生在一个翻译单元中吗?
-
Placement new 通常用于“将对象放置在已分配的内存中”也许您还需要重载placement new 运算符以与您的实现相吻合?
-
@AJG85 You cannot overload placement new: "§18.4.1.3 放置形式 这些函数是保留的,C++ 程序可能不会定义替换标准 C++ 库中版本的函数。"
-
哦,好吧,那么这个想法就到此为止了;-(
标签: c++ new-operator