在特定位置分配多态类成员
Allocate a polymorphic class member at a specific location?
我有一个类,有几个类成员和一个多态成员:
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
};
相关文章:
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 访问存储在向量C++中的结构的多态成员
- 运行时多态性 - 箭头运算符访问了错误的成员?
- 非虚拟基的多态成员类
- C++多态性:有没有办法找到对象成员函数的地址?
- 如果基类指针无法访问派生类成员函数,那么多态性有什么方便的呢?
- 无法从多态嵌套类访问包含类的成员
- C 多态性:允许模棱两可的成员类型
- 没有新成员的模板多态性派生类的大小
- 向上转换指向数据成员及其多态行为的指针
- 多态性:成员访问和吸气器给出不同的结果
- 如何在保持多态性的同时,将成员函数添加到需要它的继承类中,而不会影响其他同级类?
- 多态unique_ptr类成员
- 成员变量多态性
- 具有引用成员变量的多态性
- 使用反向引用移动多态成员的构造函数
- 将异步与多态成员函数一起使用
- 多态成员变量
- 纠结于多态成员的设计决策
- C++:多态成员会保持不变吗