使用函子或lambda的矢量深拷贝

vector deep copy using a functor or lambda

本文关键字:深拷贝 lambda      更新时间:2023-10-16

我正在尝试制作std :: shared_ptr的向量的深副本。不幸的是,我无法使用对象,因为这些指针中的大多数都是多态对象。

我尝试使用适用于std :: shared_ptr的克隆方法:

std::shared_ptr<Action> Clone ( )
{
  return std::make_shared<Action>( *this );
}

,但我仍然遇到问题。因此,我想知道(不记得我在哪里看过它)如何通过使用执行实际深层复制的函数或lambda将一个向量的内容复制到另一个向量的内容中。

让我改写,我不想要指针,我也想要尖头对象的副本。典型的作业

operator=

对于std :: vector似乎只会像通常期望的那样复制指针。

我使用的是C 11的GCC 4.8,以防它提供更优雅或简约的方法。

实际目的是使具有这些向量的类的复制构造函数提供了非共享对象,但指示相同或不同的指针:

class State
{
public:
  State ( const State & rhs )
  {
    // Deep copy Actions here?
  }

private:
  std::vector<std::shared_ptr<Action>> _actions;
};

非常感谢任何能提供帮助的人!

to deeppopy/clone a基于类型的类型,克隆函数需要虚拟

struct Action {
    virtual std::shared_ptr<Action> clone() const =0;
};
struct Paste : public Action {  
    virtual std::shared_ptr<Action> clone() const 
    {return std::make_shared<Paste>(*this);}
};

一旦拥有它,就可以使用transform和简单的lambda。

std::vector<std::shared_ptr<Action>> ActionList = {...};
auto cloner = [](const std::shared_ptr<Action>& ptr) 
    -> std::shared_ptr<Action> 
    {return ptr->clone();};
std::vector<std::shared_ptr<Action>> Copy;
std::transform(ActionList.begin(), ActionList.end(), std::back_inserter(Copy), cloner);