Hello,
I need a way to get a pointer to the start of an object in C++. This object is used inside a template so it can be any type (polymorphic or not) and could potentially be an object that uses multiple inheritance.
I found this article which describes a way to do it (see the section called "Dynamic Casts") using typeid and a dynamic_cast to void* in the case that T is a polymorphic type.
This works perfectly well on MSVC, however on GCC (4.x) it seems to fall on its arse and spits out a compiler error when it is used with a non-polymorphic type.
Does anyone know a way to:
- Make GCC behave itself, and evaluate typeid correctly
- Or another way to do this, that will compile on GCC
Below is the code I am currently using to try and achieve this.
template <typename T>
void* dynamicCastToVoidPtr(T *const ptr)
{
// This is done using a separate function to avoid a compiler error on some
// compilers about non-polymorphic types when calling startOfObject
return dynamic_cast<void*>(ptr);
}
template <typename T>
void* startOfObject(T *const ptr)
{
// In cases of multiple inheritance, a pointer may point to an offset within
// another object
// This code uses a dynamic_cast to a void* to ensure that the pointer value
// is the start of an object and not some offset within an object
void *start = static_cast<void*>(ptr);
if(start)
typeid(start = dynamicCastToVoidPtr(ptr), *ptr);
return start;
}
template <typename T>
void doSomethingWithInstance(T *const instance)
{
// Here is where I need to get a void* to the start of the object
// You can think of this as the deleteInstance function of my memory pool
// where the void* passed into freeMemory should point to the
// start of the memory that the memory pool returned previously
void *start = startOfObject(instance);
if(start)
allocator->freeMemory(start);
}
Thanks.