0

I am trying to do a deep copy of a vector of objects. I put these template classes here as an example of what I mean. In the Test Class I have in the copy constructor I have a shallow copy I believe. What I would like to know is what is the easiest way to do a deep copy of vector of object pointers like this? Do I need a for loop? I did not include a main file because I have nothing to do in it, I just would like to understand how to do the deep copy of a vector of objects in the copy constructor. What is the most elegant way to do this?

Test header

#include <iostream>
#include <vector>
#include "Test2.h"

using namespace std;

#ifndef TEST_H
#define TEST_H

class Test {
public:
    vector<Test2 *> test;
    Test();
    Test(const Test& orig);
    virtual ~Test();
private:

};

#endif /* TEST_H */

Test source

#include "Test.h"

Test::Test() {
}

Test::Test(const Test& orig) {
    this->test = orig.test;
}

Test::~Test() {
}

Test 2 header


#ifndef TEST2_H
#define TEST2_H

class Test2 {
public:
    Test2();
    Test2(const Test2& orig);
    virtual ~Test2();
private:

};

#endif /* TEST2_H */

Test2 source

#include "Test2.h"

Test2::Test2() {
}

Test2::Test2(const Test2& orig) {
}

Test2::~Test2() {
}
  • in a `main` you could test if the code you wrote does make a deep copy or not. Most elegant depends on why you have a vector of raw pointers in the first place – 463035818_is_not_an_ai Jun 24 '21 at 20:32
  • Ok. I understand that. I just thought there might be a standard way to do a deep copy like this. To copy the vector objects. – johnnyboy1899 Jun 24 '21 at 20:35
  • 1
    There is: it's to use `vector`. Alternatively, if you *need* the pointer indirection (for instance, if you plan to subclass `Test2`), then consider `vector>`. The latter will still take a for loop to deep copy, but it won't allow you to naively shallow copy either, which prevents errors. Consider who owns the data, and let your types express those invariants. `Test2*` is just uninformative as a type. – Silvio Mayolo Jun 24 '21 at 20:54
  • If you want to avoid loops, then, both, with `unique_ptr` and with raw pointers, you can use `std::transform` to create copies, so in your copy constructor something like: `std::transform( orig.test.begin(), orig.test.end(), std::back_inserter( test ), [] ( auto* origTest ) { return new Test2( *origTest ); } )` – mxmlnkn Jun 24 '21 at 21:17
  • Your code would be easier to read if you inlined the function definitions. Those definitions are so trivial that I was left wondering if it was worth the effort to scroll back and forth between source and header while reading your question. – JaMiT Jun 24 '21 at 22:01
  • You can go to [this answer](https://stackoverflow.com/a/43263477/2412846) to make your Test classes deep-copyable (while using unique_ptr). – davidhigh Jun 24 '21 at 23:09

0 Answers0