Home > Enterprise >  Deep copy with unique_ptr in map
Deep copy with unique_ptr in map

Time:01-10

I would like to create a deep copy of a class that contains a unique_ptr.

How can this be achieved?

I have the following example:

#include <iostream>
#include <unordered_map>
#include <string>
#include <memory>

class test;

typedef std::unordered_map<std::string, std::string> sMap;
typedef std::unordered_map<std::string, std::unique_ptr<test>> testMap;

class test {
    public:
    sMap     map1;
    testMap  map2; 

    test(){}

    // test(const test& t)
    // : 
    // map1(t.map1),
    // map2(t.map2) ??
    // {}
};

int main() {
    sMap myMap; 
    myMap["a"] = "b";

    std::unique_ptr<test> tobj= std::make_unique<test>();
    test& obj = *tobj;
    obj.map1 = myMap;

    test obj2;
    obj2.map2.emplace("one", std::move(tobj));

    // test obj3 (obj2); // error
    return 0;
}

How can I copy the data in the map2 when calling the copy constructor?

Kind regards

CodePudding user response:

If you want to copy the instances that the unique_ptrs point at, you need to do so manually because unique_ptrs are non-copyable. No two unique_ptrs should ever point at the same instance!

Example:

class test {
public:
    sMap     map1;
    testMap  map2; 

    test() = default;

    test(const test& other) : map1(other.map1) { // copy constructor
        for(auto&[str, ptr] : other.map2) {
            if(ptr) // recursively copy construct:
                map2.emplace(str, std::make_unique<test>(*ptr));
            else // empty pointer, put `nullptr` in there:
                map2.emplace(str, nullptr);
        }
    }

    test(test&& other) noexcept = default;      // move constructor

    test& operator=(const test& other) {        // copy assignment
        // copy construct an instance and move assign it:
        *this = test(other);
        return *this;
    }

    test& operator=(test&& other) noexcept = default; // move assignment
};
  •  Tags:  
  • c
  • Related