-1


Consider the following polymorphisme case:

class Shape {
public:
   Shape();
   virtual void draw() = 0;
   virtual ~Shape();
}

class Triangle : public Shape {
public:
   Triangle();
   void draw();
   ~Triangle();
}

class Square : public Shape {
public:
   Square();
   void draw();
   ~Square();
}

class Circle : public Shape {
public:
   Circle();
   void draw();
   ~Circle();
}

class Container {
   public:
       void addShape(string type); //Create and add instance of selected type to render_list
       void render(); //iterate through render_list and draw() each object
   private:
       vector<Shape*> render_list;
}

If render() method is called by a scheduler at fast rate: is this a good way of implementing an heterogenous collection ?
Will the vtable use be a problem for performance ?
Is there any alternative ?
Best,
Louis

4

1 回答 1

0

这是实现异构集合的好方法吗?

它会起作用,但我不会称之为好方法。问题是您vector使用原始指针 ( Shape*),它可能导致内存泄漏。更喜欢使用智能指针的容器,即std::vector<std::unique_ptr<Shape>>,而不是原始的std::vector<Shape*>

使用 vtable 会影响性能吗?

对性能的影响可以忽略不计。这是多态性的非常正确的用法。

有没有其他选择?

是的,有很多。从enums,通过附加点和/或unions。他们比这个更好吗?我不会这么说的。每个都有自己的优点和缺点,但您的方法可能是最易读的方法,这在编写代码时是一个极其重要的因素。

替代方案的另一个问题是“如果不牺牲间接性,它们都无法保持代码分离”(感谢@SoroneHaetir)。

于 2018-01-21T01:24:03.553 回答