派生类的后期分配

时间:2018-09-03 10:32:18

标签: c++

我知道派生类及其基类的内存分配为一个块。但是,在实例化基类之后,是否可以为派生部分分配额外的内存? 我想,从法律上讲,这可以通过重新分配来完成,但是额外的内存呢?

class foo
{
int a, b;
//Some properties
};

class bar : foo
{
bool initialized;
};


int main()
{
foo *one = new foo();
bar *two = //magic;
}

`

1 个答案:

答案 0 :(得分:1)

不,那是不可能的。就像您自己说的那样,对象的基础和派生部分分配在一块内存中。不仅如此,即使预先分配了更大的内存块,并且仅构造了基础部分(foo),以后也无法仅构造派生部分(bar)。

请注意,这是一个很低的级别,除非您正在实现类似std::variant<T,U,...>(很可能不是这样)之类的东西,否则切勿在常规代码中完成。

这是在给定的内存块上构造特定对象类型的方法:

int main()
{
   // this is the allocation
   char *block = new char[sizeof(bar)];

   // and this is only the construction
   foo * one = new (block) foo();
   // The memory block is big enough for bar, 
   // but there is no way to construct only the bar part
   bar * two = // magic is not possible
        // this will construct both bar and its parent foo.
        // This is bad, since the foo part is constructed twice.
        new (block) bar();

   delete[] block;
}

最好的办法是销毁并重建对象(除非您要实现低级库,否则不要这样做)

int main()
{
   // allocate the memory
   char *block = new char[sizeof(bar)];

   foo * one = new (block) foo();
   work with one....
   one->~foo(); // destroy it.

   // construct it again, using the derived type.
   bar * two = new (block) bar();
   work with two
   two->~bar();  // don't forget to destroy.

   // deallocate the memory.       
   delete[] block;
}

所有这些努力,但通过几个独立的newdelete却一无所获  对。