parallel101 / course

高性能并行编程与优化 - 课件
https://space.bilibili.com/263032155
Other
3.62k stars 532 forks source link

可以借助解引用操作变通地对 std::unique_ptr 进行深拷贝 #5

Open ltimaginea opened 2 years ago

ltimaginea commented 2 years ago

https://github.com/parallel101/course/blob/c8787cf47d60ec7a72ce6ccfc9ba6202e890c8bd/02/19/main.cpp#L32-L35

课件这里的写法是复杂又容易出错的,其实我们可以采取下面这样更安全的方式:

//C* raw_p = p.get();   // no need
func(std::make_unique<C>(*p));  // deep copy
p->do_something();  // OK, run normally

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

deep copy 示例如下:

std::unique_ptr<std::string> up1(std::make_unique<std::string>("Good morning"));

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

其它的例证: