在特定位置分配多态类成员

Allocate a polymorphic class member at a specific location?

本文关键字:多态 成员 分配 位置 定位      更新时间:2023-10-16

我有一个类,有几个类成员和一个多态成员:

class Container{
    Container::Container(){ p = new Derived();}
    Poly* p;
    A a;
    B b;
};

我想为Container::p指向的实际多态对象分配内存,在Container::b之后连续,而不是通过默认new(),因此malloc()

实现这一目标的最佳方法是什么?

在某种程度上,细节取决于Container构造函数如何决定Poly的具体类型。据推测,这种选择可能会有所不同。否则,只需在 b 之后立即声明 Derived 成员。

但是假设这个问题有意义,你只需要使用新的展示位置,并确保Container只能动态分配。小心对齐!令人高兴的是,C++11增加了对此的支持。

确保仅动态分配Container的一个好方法是使客户端代码无法访问析构函数。

对于分配大小,我可能会在类Container中定义一个自定义分配函数(operator new),传递足以确定总对象大小的参数。

但同样,细节取决于你的具体情况:这个问题没有充分说明。

这可以通过放置新位置来完成。

class Container{
    Container(){ p = new(polyAlloc) Derived(); }
    ~Container(){ p->~Poly(); /* required for placement new */ }
    Poly* p;
    A a;
    B b;
    char polyAlloc[1024]; // where the size is the max size a derived class can be
};