C++ vector of objects vs. vector of pointers to objects

前端 未结 6 571
礼貌的吻别
礼貌的吻别 2020-12-07 12:00

I am writing an application using openFrameworks, but my question is not specific to just oF; rather, it is a general question about C++ vectors in general.

I wanted

6条回答
  •  萌比男神i
    2020-12-07 12:07

    Usually I don't store classes directly in std::vector. The reason is simple: you would not know if the class is derived or not.

    E.g.:

    In headers:

    class base
    {
    public:
      virtual base * clone() { new base(*this); };
      virtual ~base(){};
    };
    class derived : public base
    {
    public:
      virtual base * clone() { new derived(*this); };
    };
    void some_code(void);
    void work_on_some_class( base &_arg );
    

    In source:

    void some_code(void)
    {
      ...
      derived instance;
      work_on_some_class(derived instance);
      ...
    }
    
    void work_on_some_class( base &_arg )
    {
      vector store;
      ...
      store.push_back(*_arg.clone());
      // Issue!
      // get derived * from clone -> the size of the object would greater than size of base
    }
    

    So I prefer to use shared_ptr:

    void work_on_some_class( base &_arg )
    {
      vector > store;
      ...
      store.push_back(_arg.clone());
      // no issue :)
    }
    

提交回复
热议问题