将派生对象分配给基类对象而不进行对象切片

时间:2015-08-14 04:41:44

标签: c++ inheritance virtual-inheritance

如何将派生对象分配给静态类型的base并且没有堆分配?

基本上,我想知道这是否可行:

Base* b = new Derived;

但没有新的和原始的指针。

1 个答案:

答案 0 :(得分:4)

您无法按Derived变量将Base对象分配给Base变量而不切片 - Derived变量不足以保存sizeof(Derived)类型的对象。想一想,因为你仍然需要那些Derived d; Base* b = &d; 字节的内存来保存一个实际的对象。

但是,您可以避免堆分配。

将其分配为自动变量:

static Derived d;
Base* b = &d;

或者作为静态变量:

//Somewhere in global scope
Derived d;
//...somewhere in function
Base* b = &d;

或者作为全球:

static char memory[sizeof(Derived)];
Base* b = new(memory)Derived;

甚至在预分配内存上使用placement new免责声明:请勿使用此实际代码):

Derived d;
Base& b = d;

最后,使用引用可以避免原始指针,但是在初始化之后你就失去了更改它的能力:

Derived

无论哪种方式,您都必须为Base对象分配足够的空间,并且必须确保其存活时间足够长,因此在原始Derived之后您无法访问{{1}}对象破坏。

相关问题