If you just want space, you're correct that can simply bind ::operator new
, but in the general case, new T[]
does more. Unfortunately, ::operator new
is overloaded, so the compiler doesn't know which one you want, so you have to "cast" it to get the right overload. tom1991t says MSVC compiles it without the cast, but I don't think the compiler is supposed to do that.
#include <functional>
#include <new>
int main() {
typedef void*(*newptr_type)(std::size_t);
typedef void(*delptr_type)(void*);
auto al = std::bind<void*>(newptr_type(::operator new), sizeof(char)*100);
auto dl = delptr_type(::operator delete);
auto field = (char*)al();
dl(field); //or just "delete[] field;"
}
Note that this is not the same as new T[]
in the general case, since this doesn't construct nor would the inverse ::operator delete
call any destructors, but for char
we don't care.
Some compilers refuse to inline function pointers under any conditions, so a functionoid would be better, including a lambda (As suggested by rcapote). This solution could handle constructors and destructors, and should run faster due to inlining.
auto al = [](){return new char[100];};
auto dl = [](char* p){delete[] p;};
auto field = (char*)al();
dl(field); //or just "delete[] field;"
Proof of compilation