EDITED: reworded question.
When new and malloc are called, the size of the block of memory to be allocated is passed:
void* malloc(size_t);
void* operator new(size_t);
is it possible to get type information, i.e. so you could do a sizeof(T) where T was the type the memory was being allocated for:
T t = new T;
I’d like to overload new and malloc but require the type information not just the size of the memory being allocated.
FURTHER EDIT:
The reason I am doing this is that I will overload malloc. This function will inspect the size of the memory being allocated and allocate from a particualr memory pool:
template <int v> struct int2type { value = v };
inline void* malloc(const std::size_t sz)
{
if(sz <= 64)
{
size_obj* ptr = malloc(nggt::core::int2type<sizeof(size_obj) + (sz % 8)>);
ptr->sz = sz;
return ptr+1;
}
else if(sz <= 128)
{
size_obj* ptr = malloc(nggt::core::int2type<sizeof(size_obj) + 128>);
ptr->sz = sz;
return ptr+1;
}
else
{
return TSuper::malloc(sz);
}
}
inline void* malloc(const nggt::core::int2type<sizeof(size_obj) + 8> sz)
{
return m_heap8.malloc(sz.value);
}
inline void* malloc(const nggt::core::int2type<sizeof(size_obj) + 16> sz)
{
return m_heap16.malloc(sz.value);
}
There are also supporintg free overloads using a freelist to return memory to a pool. Problem is I can’t use size_t sz in a template as it’s not known at compile time. If I could get the type information I could do sizeof(T) and be done!
Cheers,
Graeme
The new with the
std::size_targument is commonly known as non-placement new. Thestd::size_targument is passed in by default to let the operating system know how many bytes to allocate for the object you are creating. You, yourself, don’t need to provide it to the new declaration.Edit:
In response to your edit. It’s common practice if you are overloading the new operator to
std::size_twhich you don’t need to worry about. It’ll be handled for you.Everything else after that is all yours:
You can even use the “old” new in your call of your “new” new.
Further Edit:
In response to your next edit, don’t call your own malloc, malloc. Instead, call it some other name. If you’re writing C++, malloc has no place within your code what so ever unless you’re dealing with some legacy application. In C++, you should only be touching the new operator.