How can I create a polymorphic object on the stack?

前端 未结 12 1730
谎友^
谎友^ 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:16

    A combination of a char array and placement new would work.

    char buf[];
    A *a = NULL;
    
    switch (some_var)
    {
    case 1:
        a = new(buf) A;
        break;
    case 2:
        a = new(buf) B;
        break;
    default:
        a = new(buf) C;
        break;
    }
    
    // do stuff with a
    
    a->~A(); // must call destructor explicitly
    

提交回复
热议问题