parallel101 / parallel101/course
可以借助解引用操作变通地对 std::unique_ptr 进行深拷贝
Open
Nobody has claimed this yet.
- Dominant language
- C++
- Stars
- 4.2k
- Forks
- 556
- PR merge metrics
- No merged PRs in 30d
Description
课件这里的写法是复杂又容易出错的,其实我们可以采取下面这样更安全的方式:
//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;
其它的例证:
- 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
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Open 02/19/main.cpp at lines 32-35 and compare the current unique_ptr example with the proposed make_unique dereference approach. Update the course example to show the safer deep-copy form, then verify that the surrounding example still reads correctly and handles the intended pointer state.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 1/5
- Estimated time
- Under an hour
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 45/100