0

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?
gexicide
  • 38,535
  • 21
  • 92
  • 152

1 Answers1

2

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.

mtsvetkov
  • 885
  • 10
  • 21
  • 1
    but why a reference to the pointer and not the pointer itself? – gexicide Aug 31 '12 at 12:17
  • @gexicide: because the parameter is an lvalue its type will be deduced to reference. – Grizzly Aug 31 '12 at 12:23
  • Can you provide a reason/quote as to why this is the case? – David Rodríguez - dribeas Aug 31 '12 at 12:35
  • Good question - I'd love to know too. l- and r-values have become somewhat of a buzz-word since c++11. I also tried a simple test and it seems msvc2010 isn't complaining about the missing placement new override, nor does it define the global placement new with a reference argument. Weird... – mtsvetkov Aug 31 '12 at 13:04