问题描述
我正在尝试复制std :: shared_ptr向量的深层副本。不幸的是,我不能使用对象,因为大多数指针都指向多态对象。
I am trying to make deep copies of vectors of std::shared_ptr. Unfortunately I can't use objects, as most of those pointers are to polymorphic objects.
我尝试使用适合于std :: shared_ptr:的克隆方法:
I've tried using the clone method adapted to std::shared_ptr:
std::shared_ptr<Action> Clone ( )
{
return std::make_shared<Action>( *this );
}
但是我仍然遇到问题。
因此,我想知道(不记得在哪里看过)如何通过使用执行实际深度复制的函数或lambda将一个向量的内容复制到另一个向量中。
But I am still running into problems.So, I was wondering (can't remember where I've seen it) how can I copy the contents of one vector into another, by using a function or a lambda that performs the actual deep copy.
让我改写一下,我不仅想要指针,我也想要指向的对象的副本。
典型任务
Let me rephrase, I don't want just the pointers, I want a copy of the pointed objects too.The typical assignment
operator=
std :: vector的
似乎只复制指针,正如人们通常期望的那样。
for std::vector appears to copy only the pointers as one would normally expect.
我正在使用GCC 4.8如果可能的话,可以使用C ++ 11。
I'm using GCC 4.8 with C++11 in case it can offer any more elegant or minimalistic approach.
实际目的是使具有这些向量的类的副本构造函数提供非共享对象,但指针相同或不同:
The actual purpose is so that copy constructors of classes that have those vectors, provide non-shared objects but same or different pointers:
class State
{
public:
State ( const State & rhs )
{
// Deep copy Actions here?
}
private:
std::vector<std::shared_ptr<Action>> _actions;
};
非常感谢能提供帮助的人!
Many thanks to anyone who can help!
推荐答案
要深度复制/克隆类型擦除的类型,克隆函数需要是虚拟的
To deep-copy/clone a type-erased type the cloning function needs to be virtual
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。
Once you have that, then you can use transform
and a simple 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进行矢量深度复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!