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_ptr
s point at, you need to do so manually because unique_ptr
s are non-copyable. No two unique_ptr
s 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
};