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 概念描述不够清晰 #282

Open
Mq-b opened this issue May 20, 2024 · 3 comments
Open

std::unique_ptr 概念描述不够清晰 #282

Mq-b opened this issue May 20, 2024 · 3 comments

Comments

@Mq-b
Copy link
Contributor

Mq-b commented May 20, 2024

  • 文件路径:book/zh-cn/05-pointers.md

原文:

std::unique_ptr 是一种独占的智能指针,它禁止其他智能指针与其共享同一个对象,从而保证代码的安全

std::unique_ptr<int> pointer = std::make_unique<int>(10); // make_unique 从 C++14 引入
std::unique_ptr<int> pointer2 = pointer; // 非法

这里的逻辑经不起推敲,且描述不够好。

  1. 它禁止其它智能指针共享一个对象,从而保证代码的安全”。首先这段话里就展示不出“保证了什么安全?”当然了,还有一个冒号,然后展示了一段代码,但是这段代码也表达不了“保证了什么安全?”它只是说明了前半句而已。
  2. 文中虽然提到了“保证代码的安全”,但没有明确说明这种安全指的是什么。代码的安全性是一个广泛的概念,可以包括内存安全、资源管理、线程安全等方面。由于描述缺乏具体说明,读者可能会对安全性的含义产生困惑。
@MrShinshi
Copy link

事实上 std::unique_ptr 只能 "一定程度上的" 帮助用户防止内存泄漏, 而 不能保证代码安全, 甚至会在某些情况引入额外的灾难.

首先, C++ 本身无法禁止用户使用同一个指针构造多个智能指针(甚至可以是不同类型的智能指针),
其次, 即使使用 std::make_unique/ std::make_shared 委托构造, 也不能杜绝用户利用该智能指针实际指向的地址再次构造新的智能指针.

所以说粗略的把 "智能指针" 和 "安全" 混为一谈是一种不现实的痴心妄想, 用户不该认为, 或者误导他人可能有这样的 "安全" .

@shimachao
Copy link

大佬 fork 一个单独的版本吧

@changkun
Copy link
Owner

Thanks and PR welcome

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

4 participants