【问题标题】:Placement new With Overloaded Ordinary new Operator使用重载的普通 new 运算符放置 new
【发布时间】: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++ 实现提供(或者可能由&lt;new&gt;,我也尝试过#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


【解决方案1】:

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

#include <new>

...

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

【讨论】:

  • 确认这可以解决问题。据我了解,当前命名空间中存在new 的重载,因此它没有检查全局命名空间以找到可以工作的重载(放置new)?
  • 我不会说“在当前命名空间中”。我会说“在class 本身”。匹配函数调用涉及两个步骤 - 名称查找和重载解析。如果在类或封闭命名空间中找到该名称,则查找结束。如果查找导致多个函数,那么只有重载决议才会发挥作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多