Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ltimaginea opened this issue Jan 7, 2022 · 0 comments

Comments

@ltimaginea
Copy link

ltimaginea commented Jan 7, 2022

course/02/19/main.cpp

Lines 32 to 35 in c8787cf

C *raw_p = p.get();
func(std::move(p));
raw_p->do_something(); // 正常执行,raw_p 保留了转移前的指针

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

//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;

其它的例证:

@ltimaginea ltimaginea changed the title 可以借助移动操作变通地对 unique_ptr 进行深拷贝 可以借助移动操作变通地对 std::unique_ptr 进行深拷贝 Jan 7, 2022
@ltimaginea ltimaginea changed the title 可以借助移动操作变通地对 std::unique_ptr 进行深拷贝 可以借助解引用操作变通地对 std::unique_ptr 进行深拷贝 Feb 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant