How can I create a polymorphic object on the stack?

前端 未结 12 1771
谎友^
谎友^ 2021-01-12 05:40

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         


        
12条回答
  •  误落风尘
    2021-01-12 06:31

    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;
    }
    

提交回复
热议问题