可以在C++可以延迟结合。使用构图时无需堆内存?
后期结合或运行时 - 造态性需要两件事:基本指针和虚拟方法。
class FrameWorkClassBase {
public:
virtual void method() = 0;
};
class FrameWorkClassDerived: public FrameWorkClassBase {
public:
virtual void method() override { ... }
}
class ProductionConsumerClass { // uses composition
public:
void method() {
this->m_sptr->method(); // dynamic dispatch
}
private:
// ptr to base class, composition at work
std::shared_ptr<FrameWorkClassBase> m_sptr =
std::make_shared<FrameWorkClassDerived>();
}
似乎有偏见是将堆存储器用于多态对象创建而不是堆叠分配的对象,尤其是在使用“多态对象”作为组件对象时。这是一个要求:整个C ++语言的性质是否迫使将堆内存使用用于“多态组件对象”?是否有任何设计模式可以克服对“多态组件对象”使用堆内存的需求?
注意:我不想使用基类L值参考(FrameworkClassBase&amp;
)作为ProductionConsumerClass中的数据成员
,因为我没有终身企业/所有权引用对象。
late-binding or runtime-polymorphism needs 2 things: a base pointer and a virtual method.
class FrameWorkClassBase {
public:
virtual void method() = 0;
};
class FrameWorkClassDerived: public FrameWorkClassBase {
public:
virtual void method() override { ... }
}
class ProductionConsumerClass { // uses composition
public:
void method() {
this->m_sptr->method(); // dynamic dispatch
}
private:
// ptr to base class, composition at work
std::shared_ptr<FrameWorkClassBase> m_sptr =
std::make_shared<FrameWorkClassDerived>();
}
there seems to be a bias towards using heap memory for polymorphic object creation rather than stack allocated objects, especially when it comes to using "polymorphic object" as component objects. Is this a requirement: is it the nature of the C++ language as a whole that forces the use of heap memory for "polymorphic component objects" ? Are there any design patterns that overcome the need for using heap memory for "polymorphic component objects" ?
Note: I do not want to use base class l-value reference(FrameWorkClassBase&
) as a data member in ProductionConsumerClass
as i do not have life-time-guarantee/ownership of the referred object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
无需使用堆分配来延迟绑定以进行工作:
在上面的示例中,没有进行堆分配,所有参考变量均为type
base&amp;
。较晚的装订效果很好。There is no need to use heap allocation for late binding to work:
In the example above, no heap allocation takes place and all reference variables are of type
Base&
. Late binding works just fine.