Creating a new object from dynamic type info

前端 未结 8 989
南旧
南旧 2020-12-05 05:22

In C++, is there any way to query the type of an object and then use that information to dynamically create a new object of the same type?

For example, say I have a

8条回答
  •  伪装坚强ぢ
    2020-12-05 05:52

    There's only some hacky ways to do this.

    The first and IMHO the ugliest is:

    Base * newObjectOfSameType( Base * b )
    {
      if( dynamic_cast( b ) ) return new Foo;
      if( dynamic_cast( b ) ) return new Bar;
    }
    

    Note that this will only work if you have RTTI enabled and Base contains some virtual function.

    The second an neater version is to add a pure virtual clone function to the base class

    struct Base { virtual Base* clone() const=0; }
    struct Foo : public Base { Foo* clone() const { return new Foo(*this); }
    struct Bar : public Base { Bar* clone() const { return new Bar(*this); }
    
    Base * newObjectOfSameType( Base * b )
    {
      return b->clone();
    }
    

    This is much neater.

    One cool/interesting thing about this is that Foo::clone returns a Foo*, while Bar::clone returns a Bar*. You might expect this to break things, but everything works due to a feature of C++ called covariant return types.

    Unfortunately covariant return types don't work for smart pointers, so using sharted_ptrs your code would look like this.

    struct Base { virtual shared_ptr clone() const=0; }
    struct Foo : public Base { shared_ptr clone() const { return shared_ptr(new Foo(*this) ); }
    struct Bar : public Base { shared_ptr clone() const { return shared_ptr(new Bar(*this)); }
    
    shared_ptr newObjectOfSameType( shared_ptr b )
    {
      return b->clone();
    }
    

提交回复
热议问题