I want to implement my own heap allocation function to do the same as the C++ new operator when it comes to allocating elements of a class type. My allocation function (for Windows) does not use the new operator or the standard library, but only HeapAlloc. So my problem is when allocating elements of a class type :
// Allocation function definition.
template <typename Type>
Type* Alloc(int Count) {
return reinterpret_cast<Type*>(HeapAlloc(GetProcessHeap(), 0, sizeof(Type) * Count));
}
// Allocation function use.
Alloc<Class>(5);
The function allocates 5 Class, which is a simple class with a single default constructor. The constructor does not get called, and I can see why. The only thing I do is allocate some memory and reinterpret_cast it.
Where I get confused though, is with the new operator :
new Class[5];
The default constructor gets called! The new operator is in the end (on Windows of course) also calling HeapAlloc. The function does some other stuff too, but none of it seems to really have an impact on the final result.
How can new call the constructors of each element it allocates, and can I do the same? Or is this just some built-in feature (even though it's part of the standard library)?
So called
newexpressions (new int[5]) calloperator new(similar tomalloc) and the objects' constructor. You can use placementnewexpressions orstd::construct_atfrom C++20 to call the constructors manually. Your code could end up looking like this:Then you can use the functions like this:
Note that using
std::construct_at/std::destroy_ator placement new expressions/manual destructor calls doesn't really make a difference.std::construct_atandstd::destroy_atareconstexprand more explicit or perhaps easier to understand, but you can do it either way.