I have a std::vector<A*>
which I need to deep copy to another vector using A::Clone()
.
Instead of using handwritten loops, I was wondering whether I could use for_each
or any Standard Library algorithm for this.
Copying a pointer does not copy the corresponding object, leading to surprises if two pointers inadvertently points to the same object. Destroying a pointer does not destroy its object, leading to memory leaks.
You can store pointers in a vector just like you would anything else. Declare a vector of pointers like this: vector<MyClass*> vec; The important thing to remember is that a vector stores values without regard for what those values represent.
The appropriate algorithm is std::transform and you can turn member function invocation into a unary functor with std::mem_fun
Example:
#include <vector>
#include <functional>
#include <algorithm>
#include <iterator>
class X
{
public:
X* clone();
};
int main()
{
std::vector<X*> vec1, vec2;
std::transform(vec1.begin(), vec1.end(), std::back_inserter(vec2), std::mem_fun(&X::clone));
}
If the target vector is already the same size as the input range, you can pass vec2.begin()
as the third argument. Use back_inserter
if the target is empty (or you want to append to it).
Perhaps something like this would work:
class DeepCopy {
public:
A* operator() (A* aP) {
return aP->Clone();
}
}
int main()
{
vector<A*> vA;
vector<A*> vA2;
transform(vA.begin(), vA.end(), back_inserter(vA2), DeepCopy());
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With