-
Notifications
You must be signed in to change notification settings - Fork 72
Update no_more_new.md with some bad demo #42
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
Conversation
|
1 goto不是为了这个原因发明的 |
| 这就会让编写程序的人精神紧绷,更加仔细的检查 `new` 和 `delete` 是否配对,`goto EXIT` 会不会有其他负面影响。享受不到编程的快乐就算了,反而在遭罪。。。 | ||
|
|
||
| 此外,`new` 和 `delete` 使用不配套时,也会导致严重的错误。由于 `new` 和 `delete` 是基于指针操作的,但是在很庞大的代码系统中我们拿到一个指针 `data *ptr` 后。这个 `ptr` 是空指针吗?还是已经被释放了吗?还是已经有内存了?还是交由我们申请内存?很容易忘记 `new` 而直接 `delete`,或者对同一个指针 `new` 了两次,或者没有 `delete` 等等。看到屎山代码后的坏心情会导致代码维护难度指数级增加。 | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
此处表达的其实是所有权的问题,简而言之所有权不明确。
谁是所有者?
务必明确表达出所有权。试想一下,你的程序是用传统 C++ 编写的,只能使用原始指针来表达指针、引用、std::unique_ptr 或 std::shared_ptr 这四种传参方式的所有权语义。
- 传统 C++ 的关键问题是,谁是所有者?
下面的代码说明了我的观点:
void func(double* ptr){
...
}
double* ptr = new double[5];
func(ptr);关键问题是,谁是资源的所有者?
是使用该数组的 func 中的被调用方,还是创建该数组的 func 的调用方?
如果 func 是所有者,那么它必须释放该资源。如果不是,则 func 不可以释放资源。
这种情况不能令人满意。如果 func 不释放资源,可能会发生内存泄露。如果 func 释放了资源,可能会导致未定义行为。
因此,所有权需要记录在文档中。使用现代 C++ 中的类型系统来定义所有权的契约是朝正确方向迈出的一大步,可以消除文档的模糊性。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
几十万行的代码会有几万个函数,用文档记录感觉不现实。。。
现代 C++ 中的类型系统来定义所有权的契约
我的知识盲区,去学习一下
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
学习了 💯
额外的,我忙里偷闲每天看一些 C++,可能后面还会以章节为单位提 PR (