我想知道是否有办法在实例化后填充对象。说一个从类 Foo 实例化的对象,其实现如下:
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;
}
};
然后通过创建对象的实例Foo* object = new Foo();
。有没有办法说添加到对象以便(size_t)object
或 sizeof(*object)
将其显示为更大的对象?此外,当说将 char* 之类的标准数据类型投射到该对象时,是否有办法填充该投射以使 char* 适合它投射到的对象的大小?我有点好奇地问了这些问题,因为我觉得它可能会解决我在程序中遇到的问题。这是具体的上下文:
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;
}
这样做的问题是它有点体面地将其转换为 T 对象,但大小仍然是缓冲区的大小。在 main 中执行sizeof(*object)
将显示我认为对象的大小,但是如果我将(size_t) object
from Foo* object = new Foo()
与(size_t)differentObj
from Foo* differentObj = AddObject()
进行比较,(size_t)differentObj
则将(size_t)buffer
与(size_t)object
. 也许是因为我不明白代表的内容与内存中对象的位数是否size_t
不同,我不确定。sizeof
至少据我了解sizeof
,它代表变量或类型占用的内存量(以字节为单位)。