如何在堆栈上创建多态对象? [英] How can I create a polymorphic object on the stack?
本文介绍了如何在堆栈上创建多态对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在堆栈上分配多态对象?我正在尝试做类似的事情(试图避免用new分配堆)?
How do I allocate a polymorphic object on the stack? I'm trying to do something similar to (trying to avoid heap allocation with new)?:
A* a = NULL;
switch (some_var)
{
case 1:
a = A();
break;
case 2:
a = B(); // B is derived from A
break;
default:
a = C(); // C is derived from A
break;
}
推荐答案
由于无法在条件块中创建自动对象或临时对象,因此无法构造单个函数以使其工作,因为阻止.
You can't structure a single function to work like that, since automatic or temporary objects created inside a conditional block can't have their lifetimes extended into the containing block.
我建议将多态行为重构为一个单独的函数:
I'd suggest refactoring the polymorphic behaviour into a separate function:
void do_something(A&&);
switch (some_var)
{
case 1:
do_something(A());
break;
case 2:
do_something(B()); // B is derived from A
break;
default:
do_something(C()); // C is derived from A
break;
}
这篇关于如何在堆栈上创建多态对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文