parallel101 / parallel101/course

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

Open
#5 0 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C++
Stars
4.2k
Forks
556
PR merge metrics
No merged PRs in 30d

Description

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;

其它的例证:

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.