unique_ptr 拷贝的方法


unique_ptr 拷贝的方法

std::unique_ptr Deep Copy

虽然 std::unique_ptr 删除了 copy constructor 和 copy assignment operator ,但其实我们可以借助解引用操作变通地对 std::unique_ptr 进行拷贝。

deep copy 示例如下:

std::unique_ptr up1(std::make_unique("Good morning"));

// copy construct!
std::unique_ptr up2(std::make_unique(*up1));
// safe copy construct!
std::unique_ptr up3(up1 ? std::make_unique(*up1) : nullptr);
// copy assignment!
up2 = std::make_unique(*up1);
// safe copy assignment!
up3 = up1 ? std::make_unique(*up1) : nullptr;

其它的例证:

  • Google tensorflow : unique_ptr - in copy assignment operator
  • Microsoft terminal : unique_ptr - in copy constructor
  • 《Effective Modern C++》,Item22,其中的 class Widget 的 copy constructor 和 copy assignment operator 的实现,见 EffectiveModernCppChinese/item22.md · GitHub