Вопрос

I have overloaded the new operator for a type X to use some memory pool. My new operator takes no user-defined arguments, thus, the only argument is the size of the object of type size_t. At another part of the program, I need placement new for the same type, like this:

new (ptr) X();

(where ptr is a pointer to a preallocated memory location)

It seems that my overload of the new operator for the type shadows placement new. At least, the compiler complains:

error: no matching function for call to ‘X::operator new(long unsigned int, X*&)’
note: candidate is:
note: static void* X::operator new(size_t)
note:   candidate expects 1 argument, 2 provided

The candidate is my overload of the new operator. My questions are:

  • Why doesn't the compiler recognize that I want to use placement new?
  • How can I use it anyway?
  • WTF is the type X*& shown in the error message?
Это было полезно?

Решение

Overriding TypeName::operator new (size_t) requires you to also override the placement new operator (the opposite is not required). That's why the compiler is complaining. (Makes sense - if you're doing something strange during allocation, you might want to do that at the specified place in the placement new operator as well, with the reverse not necessarily true). And X*& is just a reference to the pointer where you want the new object.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top