C++ copies of objects with abstract class pointers

删除回忆录丶 提交于 2021-02-07 07:59:34

问题


Consider the Container class, which basically stores a vector of unique_ptrs of Box objects and can perform some computations on them.

class Container
{
  private:
    std::vector<std::unique_ptr<Box> > boxes_;
  public:
    Container(std::vector<std::unique_ptr<Box> > &&boxes): boxes_(std::move(boxes)){}
    double TotalVolume() { /* Iterate over this->boxes_ and sum */ }
};

Here, Box is an abstract class that has a pure virtual method such as double Box::Volume().

Now, suppose that I instantiate a container in the main program as:

std::vector<std::unique_ptr<Box> > x;
x.push_back(std::move(std::unique_ptr<Box>(new SquareBox(1.0)));
x.push_back(std::move(std::unique_ptr<Box>(new RectangularBox(1.0, 2.0, 3.0)));
Container c(x);

How do I make copies of c? I would like a function that makes copies of the underlying Box object in boxes_, but I think it's hard to do this with base classes?


回答1:


One way to make your copies is to have a "Copy" virtual method in your base class. This method would create a copy of the current object and return a (unique) pointer to it. If there are any contained pointers within the class, they'd need new copies created as well (a deep copy).

Other approaches exist. For instance, you could test each object in the vector to determine its type (using dynamic_cast), but this is ugly, inefficient, and very error prone.



来源:https://stackoverflow.com/questions/40315760/c-copies-of-objects-with-abstract-class-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!