Skip to content

Commit bf6b092

Browse files
committed
book: translation of ch05
Update #12
1 parent e01ebc0 commit bf6b092

File tree

9 files changed

+294
-84
lines changed

9 files changed

+294
-84
lines changed

book/en-us/05-pointers.md

+189
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,199 @@ order: 5
66

77
# Chapter 05 Smart Pointers and Memory Management
88

9+
[TOC]
10+
11+
## 5.1 RAII and Reference Counting
12+
13+
Programmers who understand `Objective-C`/`Swift`/`JavaScript` should know the concept of reference counting. The reference count is counted to prevent memory leaks.
14+
The basic idea is to count the number of dynamically allocated objects. Whenever you add a reference to the same object, the reference count of the referenced object is incremented once.
15+
Each time a reference is deleted, the reference count is decremented by one. When the reference count of an object is reduced to zero, the pointed heap memory is automatically deleted.
16+
17+
In traditional C++, "remembering" to manually release resources is not always a best practice. Because we are likely to forget to release resources and lead to leakage.
18+
So the usual practice is that for an object, we apply for space when constructor, and free space when the destructor (called when leaving the scope).
19+
That is, we often say that the RAII resource acquisition is the initialization technology.
20+
21+
There are exceptions to everything, we always have the need to allocate objects on free storage. In traditional C++ we have to use `new` and `delete` to "remember" to release resources. C++11 introduces the concept of smart pointers, using the idea of ​​reference counting, so that programmers no longer need to care about manually releasing memory.
22+
These smart pointers include `std::shared_ptr`/`std::unique_ptr`/`std::weak_ptr`, which need to include the header file `<memory>`.
23+
24+
> Note: The reference count is not garbage collection. The reference count can recover the objects that are no longer used as soon as possible, and will not cause long waits during the recycling process.
25+
> More clearly and clearly indicate the life cycle of resources.
26+
27+
## 5.2 `std::shared_ptr`
28+
29+
`std::shared_ptr` is a smart pointer that records how many `shared_ptr` points to an object, eliminating the display call `delete`, which automatically deletes the object when the reference count becomes zero.
30+
31+
But not enough, because using `std::shared_ptr` still needs to be called with `new`, which makes the code a certain degree of asymmetry.
32+
33+
`std::make_shared` can be used to eliminate the explicit use of `new`, so `std::make_shared` will allocate the objects in the generated parameters.
34+
And return the `std::shared_ptr` pointer of this object type. For example:
35+
36+
```cpp
37+
#include <iostream>
38+
#include <memory>
39+
void foo(std::shared_ptr<int> i)
40+
{
41+
(*i)++;
42+
}
43+
int main()
44+
{
45+
// auto pointer = new int(10); // illegal, no direct assignment
46+
// Constructed a std::shared_ptr
47+
auto pointer = std::make_shared<int>(10);
48+
foo(pointer);
49+
std::cout << *pointer << std::endl; // 11
50+
// The shared_ptr will be destructed before leaving the scope
51+
return 0;
52+
}
53+
```
54+
55+
`std::shared_ptr` can get the raw pointer through the `get()` method and reduce the reference count by `reset()`.
56+
And see the reference count of an object by `use_count()`. E.g:
57+
58+
```cpp
59+
auto pointer = std::make_shared<int>(10);
60+
auto pointer2 = pointer; // reference count+1
61+
auto pointer3 = pointer; // reference count+1
62+
int *p = pointer.get(); // no increase of reference count
63+
std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl; // 3
64+
std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl; // 3
65+
std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl; // 3
66+
67+
pointer2.reset();
68+
std::cout << "reset pointer2:" << std::endl;
69+
std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl; // 2
70+
std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl; // 0, pointer2 has reset
71+
std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl; // 2
72+
pointer3.reset();
73+
std::cout << "reset pointer3:" << std::endl;
74+
std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl; // 1
75+
std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl; // 0
76+
std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl; // 0, pointer3 has reset
77+
```
78+
79+
## 5.3 `std::unique_ptr`
80+
81+
`std::unique_ptr` is an exclusive smart pointer that prohibits other smart pointers from sharing the same object, thus keeping the code safe:
82+
83+
```cpp
84+
std::unique_ptr<int> pointer = std::make_unique<int>(10); // make_unique was introduced in C++14
85+
std::unique_ptr<int> pointer2 = pointer; // illegal
86+
```
87+
88+
> `make_unique` is not complicated. C++11 does not provide `std::make_unique`, which can be implemented by itself:
89+
>
90+
> ```cpp
91+
> template<typename T, typename ...Args>
92+
> std::unique_ptr<T> make_unique( Args&& ...args ) {
93+
> return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
94+
> }
95+
> ```
96+
>
97+
> As for why it wasn't provided, Herb Sutter, chairman of the C++ Standards Committee, mentioned in his [blog](https://herbsutter.com/gotw/_102/) that it was because they were forgotten.
98+
99+
Since it is monopolized, in other words, it cannot be copied. However, we can use `std::move` to transfer it to other `unique_ptr`, for example:
100+
101+
```cpp
102+
#include <iostream>
103+
#include <memory>
104+
105+
struct Foo {
106+
Foo() { std::cout << "Foo::Foo" << std::endl; }
107+
~Foo() { std::cout << "Foo::~Foo" << std::endl; }
108+
void foo() { std::cout << "Foo::foo" << std::endl; }
109+
};
110+
111+
void f(const Foo &) {
112+
std::cout << "f(const Foo&)" << std::endl;
113+
}
114+
115+
int main() {
116+
std::unique_ptr<Foo> p1(std::make_unique<Foo>());
117+
118+
// p1 is not empty, prints
119+
if (p1) p1->foo();
120+
{
121+
std::unique_ptr<Foo> p2(std::move(p1));
122+
123+
// p2 is not empty, prints
124+
f(*p2);
125+
126+
// p2 is not empty, prints
127+
if(p2) p2->foo();
128+
129+
// p1 is empty, no prints
130+
if(p1) p1->foo();
131+
132+
p1 = std::move(p2);
133+
134+
// p2 is empty, no prints
135+
if(p2) p2->foo();
136+
std::cout << "p2 was destroied" << std::endl;
137+
}
138+
// p1 is not empty, prints
139+
if (p1) p1->foo();
140+
141+
// Foo instance will be destroied when leaving the scope
142+
}
143+
```
144+
145+
## 5.4 `std::weak_ptr`
146+
147+
If you think about `std::shared_ptr` carefully, you will still find that there is still a problem that resources cannot be released. Look at the following example:
148+
149+
```cpp
150+
#include <iostream>
151+
#include <memory>
152+
153+
class A;
154+
class B;
155+
156+
class A {
157+
public:
158+
std::shared_ptr<B> pointer;
159+
~A() {
160+
std::cout << "A was destroied" << std::endl;
161+
}
162+
};
163+
class B {
164+
public:
165+
std::shared_ptr<A> pointer;
166+
~B() {
167+
std::cout << "B was destroied" << std::endl;
168+
}
169+
};
170+
int main() {
171+
std::shared_ptr<A> a = std::make_shared<A>();
172+
std::shared_ptr<B> b = std::make_shared<B>();
173+
a->pointer = b;
174+
b->pointer = a;
175+
176+
return 0;
177+
}
178+
```
179+
180+
The result is that A and B will not be destroyed. This is because the pointer inside a, b also references `a, b`, which makes the reference count of `a, b` become 2, leaving the scope. When the `a, b` smart pointer is destructed, it can only cause the reference count of this area to be decremented by one. This causes the memory area reference count pointed to by the `a, b` object to be non-zero, but the external has no The way to find this area, it also caused a memory leak, as shown in Figure 5.1:
181+
182+
![Figure 5.1](../../assets/figures/pointers1.png)
183+
184+
The solution to this problem is to use the weak reference pointer `std::weak_ptr`, which is a weak reference (compared to `std::shared_ptr` is a strong reference). A weak reference does not cause an increase in the reference count. When a weak reference is used, the final release process is shown in Figure 5.2:
185+
186+
![Figure 5.2](../../assets/figures/pointers2.png)
187+
188+
In the above figure, only B is left in the last step, and B does not have any smart pointers to reference it, so this memory resource will also be released.
189+
190+
`std::weak_ptr` has no `*` operator and `->` operator, so it can't operate on resources. Its only function is to check if `std::shared_ptr` exists, its `expired() The ` method can return `true` when the resource is not released, otherwise it returns `false`.
191+
192+
## Conclusion
193+
194+
The technology of smart pointers is not novel. It is a common technology in many languages. Modern C++ introduces this technology, which eliminates the abuse of `new`/`delete` to a certain extent. It is a more mature technology. Programming paradigm.
195+
9196
[Table of Content](./toc.md) | [Previous Chapter](./04-containers.md) | [Next Chapter: Regular Expression](./06-regex.md)
10197
11198
## Further Readings
12199
200+
- [Why does C++11 have `make_shared` but not `make_unique`](http://stackoverflow.com/questions/12580432/why-does-c11-have-make-shared-but-not-make-unique)
201+
13202
## Licenses
14203
15204
<a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-nc-nd/4.0/88x31.png" /></a><br />This work was written by [Ou Changkun](https://changkun.de) and licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/4.0/">Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License</a>. The code of this repository is open sourced under the [MIT license](../../LICENSE).

book/en-us/toc.md

+1
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
+ 5.1 RAII and reference counting
6969
+ 5.2 `std::shared_ptr`
7070
+ 5.3 `std::unique_ptr`
71+
+ 5.4 `std::weak_ptr`
7172
- [**Chapter 06 Regular Expression**](./06-regex.md)
7273
+ 6.1 Introduction
7374
+ Ordinary characters

book/zh-cn/05-pointers.md

+8-8
Original file line numberDiff line numberDiff line change
@@ -44,12 +44,12 @@ void foo(std::shared_ptr<int> i)
4444
}
4545
int main()
4646
{
47-
// auto pointer = new int(10); // 非法, 不允许直接赋值
48-
// 构造了一个 std::shared_ptr
47+
// auto pointer = new int(10); // illegal, no direct assignment
48+
// Constructed a std::shared_ptr
4949
auto pointer = std::make_shared<int>(10);
5050
foo(pointer);
5151
std::cout << *pointer << std::endl; // 11
52-
// 离开作用域前,shared_ptr 会被析构,从而释放内存
52+
// The shared_ptr will be destructed before leaving the scope
5353
return 0;
5454
}
5555
```
@@ -137,7 +137,7 @@ int main() {
137137
}
138138
```
139139
140-
## 5.4 std::weak_ptr
140+
## 5.4 `std::weak_ptr`
141141
142142
如果你仔细思考 `std::shared_ptr` 就会发现依然存在着资源无法释放的问题。看下面这个例子:
143143
@@ -165,13 +165,13 @@ int main() {
165165
}
166166
```
167167
168-
运行结果是 A, B 都不会被销毁,这是因为 a,b 内部的 pointer 同时又引用了 `a,b`,这使得 `a,b` 的引用计数均变为了 2,而离开作用域时,`a,b` 智能指针被析构,却只能造成这块区域的引用计数减一,这样就导致了 `a,b` 对象指向的内存区域引用计数不为零,而外部已经没有办法找到这块区域了,也就造成了内存泄露,如图所示
168+
运行结果是 A, B 都不会被销毁,这是因为 a,b 内部的 pointer 同时又引用了 `a,b`,这使得 `a,b` 的引用计数均变为了 2,而离开作用域时,`a,b` 智能指针被析构,却只能造成这块区域的引用计数减一,这样就导致了 `a,b` 对象指向的内存区域引用计数不为零,而外部已经没有办法找到这块区域了,也就造成了内存泄露,如图 5.1
169169
170-
![](../../assets/figures/pointers1.png)
170+
![图 5.1](../../assets/figures/pointers1.png)
171171
172-
解决这个问题的办法就是使用弱引用指针 `std::weak_ptr`,`std::weak_ptr`是一种弱引用(相比较而言 `std::shared_ptr` 就是一种强引用)。弱引用不会引起引用计数增加,当换用弱引用时候,最终的释放流程如下图所示
172+
解决这个问题的办法就是使用弱引用指针 `std::weak_ptr`,`std::weak_ptr`是一种弱引用(相比较而言 `std::shared_ptr` 就是一种强引用)。弱引用不会引起引用计数增加,当换用弱引用时候,最终的释放流程如图 5.2 所示
173173
174-
![](../../assets/figures/pointers2.png)
174+
![图 5.2](../../assets/figures/pointers2.png)
175175
176176
在上图中,最后一步只剩下 B,而 B 并没有任何智能指针引用它,因此这块内存资源也会被释放。
177177

book/zh-cn/toc.md

+1
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
+ 5.1 RAII 与引用计数
6969
+ 5.2 `std::shared_ptr`
7070
+ 5.3 `std::unique_ptr`
71+
+ 5.4 `std::weak_ptr`
7172
- [**第 6 章 标准库: 正则表达式**](./06-regex.md)
7273
+ 6.1 正则表达式简介
7374
+ 普通字符

code/5/5.1.cpp

-66
This file was deleted.

code/5/5.1.shared.ptr.a.cpp

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
//
2+
// 5.1.shared.ptr.cpp
3+
// chapter 05 start pointers and memory management
4+
// modern c++ tutorial
5+
//
6+
// created by changkun at changkun.de
7+
// https://github.com/changkun/modern-cpp-tutorial
8+
//
9+
10+
#include <iostream>
11+
#include <memory>
12+
13+
void foo(std::shared_ptr<int> i)
14+
{
15+
(*i)++;
16+
}
17+
18+
int main()
19+
{
20+
// auto pointer = new int(10); // illegal, no direct assignment
21+
// std::shared_ptr construction
22+
auto pointer = std::make_shared<int>(10);
23+
auto pointer2 = pointer; // reference count + 1
24+
auto pointer3 = pointer; // reference count + 1
25+
26+
27+
foo(pointer);
28+
std::cout << *pointer << std::endl; // 11
29+
int *p = pointer.get(); // does not increase reference count
30+
31+
std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl;
32+
std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl;
33+
std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl;
34+
35+
pointer2.reset();
36+
std::cout << "reset pointer2:" << std::endl;
37+
std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl;
38+
std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl;
39+
std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl;
40+
41+
pointer3.reset();
42+
std::cout << "reset pointer3:" << std::endl;
43+
std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl;
44+
std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl;
45+
std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl;
46+
// std::cout << *pointer << std::endl; // reference count equals 0, illegal access
47+
48+
49+
// Before leaving the scope, the pointer is destructed and
50+
// the reference count is reduced to 0
51+
return 0;
52+
}

0 commit comments

Comments
 (0)