使用函子或lambda的矢量深拷贝
vector deep copy using a functor or lambda
我正在尝试制作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);
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 可组合的lambda/std::函数与std::可选
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 如何将lambda作为模板类的成员函数参数
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 与浅拷贝构造函数和深拷贝构造函数混淆
- C++ 一个lambda浅拷贝const Type&如果它被赋予一个命名捕获,如[copy=val](){}?
- 如何将深拷贝构造函数实现到链表中?
- 在函数中传递带有指针成员的结构是浅拷贝或深拷贝在 C 中
- C++ 标准::字符串意外更改。我认为这个问题是关于深和浅拷贝的
- 如何正确制作抽象类的深拷贝?
- 从功能返回时,向量的深拷贝行为
- 使用函子或lambda的矢量深拷贝
- STD向量C++ - 深拷贝或浅拷贝
- c++浅/深拷贝
- 懒惰复制-如何从浅拷贝创建深拷贝
- QVector::replace()创建深拷贝吗?
- multi_array_view没有深拷贝的作业
- 如何做深拷贝