How can I create a polymorphic object on the stack?

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

    It is possible, but it's a lot of effort to do cleanly (without manual placement new and exposed raw buffers, that is).

    You're looking at something like Boost.Variant, modified to restrict the types to a base class and some derived classes, and to expose a polymorphic reference to the base type.

    This thing (PolymorphicVariant ?) would wrap all the placement new stuff for you (and also take care of safe destruction).

    If it's really what you want, let me know and I'll give you a start. Unless you really need exactly this behaviour though, Mike Seymour's suggestion is more practical.

提交回复
热议问题