I was wondering if there was a way to pad an object after instantiation. Say an object instantiated from class Foo with the implementation below:
class Foo
{
size_t addr;
unsigned allocationNum;
public:
Foo()
{
addr = (size_t)this;
allocationNum = 0;
}
~Foo()
{
addr = 0;
allocationNum = 0;
}
void SetAllocNum(unsigned nAllocationNum)
{
allocationNum = nAllocationNum;
}
unsigned GetAllocNum() const
{
return allocationNum;
}
size_t GetAddress() const
{
return addr;
}
};
The instance of the object then is created through Foo* object = new Foo();
. Is there a way to say add to the object so that (size_t)object
or sizeof(*object)
shows it as a bigger object? Also when say casting a standard data type like char* to this object is there a way to pad that cast to make the char* fit the size of the object it is casting to? I ask these questions somewhat out of curiosity and because I feel it may solve a problem I have with my program. Here is the specific context:
T* AddObject()
{
T* object = new T(); // Here is the new object T=Foo in this case.
*(T*)(buffer+position) = *object; // Being stored in a char* buffer at current empty position
T* returnValue = &(*(reinterpret_cast<T*>(buffer+position)));
// ^ Here I try casting the char* buffer@position with the object contents stored inside the buffer.
return returnValue;
}
Problem with this is that it is casting it to a T object somewhat decently but the size is still that of the buffer. Performing sizeof(*object)
in main will display what I think size of the object should be but if I compare the (size_t) object
from Foo* object = new Foo()
with the (size_t)differentObj
from Foo* differentObj = AddObject()
the (size_t)differentObj
will be the the same as (size_t)buffer
but not the same as (size_t)object
. Maybe its because I don't understand what size_t
is representing differently than sizeof
whether its the number of bits the objects in memory have or not I'm not sure. At least from what I understand sizeof
represents the amount of memory in bytes that a variable or type occupies.