I was thinking about some memory pool/allocation stuff I might write so I came up with this operator new overload that I want to use to facilitate reuse of memory. I’m wondering if there are any problems you guys can think of with my implementation (or any other possible ones).
#include <cstddef>
namespace ns {
struct renew_t { };
renew_t const renew;
}
template<typename T>
inline void * operator new(std::size_t size, T * p, ns::renew_t renew_constant) {
p->~T();
return p;
}
template<typename T>
inline void operator delete(void *, T *, ns::renew_t renew_constant) { }
It can be used like this
int main() {
foo * p(new foo()); // allocates memory and calls foo's default constructor
new(p, ns::renew) foo(42); // calls foo's destructor, then calls another of foo's constructors on the same memory
delete p; // calls foo's destructor and deallocates the memory
}
SHOULD be good, as long as you don’t try something crazy and try to renew a subclass. Since you said this is for a pool, it should be fine.
That said, my only question is – what is more legible? This is a question of taste, but imagine that somebody else might need to look at the code. You’re basically just contracting two simple and obvious statements into one that requires deeper knowledge of what the code internally does.
In my pool functions, I typically had two separate methods, one to destroy and one to construct, both them essentially doing what you do here (p->~T and new(p) T()), but at least you know exactly what they did.