-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathC++SmartPointer20201023.html
420 lines (310 loc) · 31.2 KB
/
C++SmartPointer20201023.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
<!DOCTYPE html>
<html lang=en>
<head>
<!-- so meta -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="HandheldFriendly" content="True">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=5" />
<meta name="description" content="早在C++98/03标准的时候,C++就引入了智能指针(Smart Pointer)的概念来帮助程序员对于堆内存进行自动回收。 引入的目地主要是:对指针的行为进行一定的规范。这有很多的好处,比如: 这样可以避免野指针的出现 这样可以避免错误的对于同一块地址进行两次释放 释放不在使用的内存资源,避免内存的泄漏.智能指针使得为我们能够更加安全有效的使用(共享)同一块堆空间.">
<meta property="og:type" content="article">
<meta property="og:title" content="C++ Smart Pointer(智能指针)">
<meta property="og:url" content="https://tblgsn.github.io/C++SmartPointer20201023.html">
<meta property="og:site_name" content="tblgsn的个人博客">
<meta property="og:description" content="早在C++98/03标准的时候,C++就引入了智能指针(Smart Pointer)的概念来帮助程序员对于堆内存进行自动回收。 引入的目地主要是:对指针的行为进行一定的规范。这有很多的好处,比如: 这样可以避免野指针的出现 这样可以避免错误的对于同一块地址进行两次释放 释放不在使用的内存资源,避免内存的泄漏.智能指针使得为我们能够更加安全有效的使用(共享)同一块堆空间.">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2020-10-23T13:35:00.000Z">
<meta property="article:modified_time" content="2025-01-22T09:14:47.021Z">
<meta property="article:author" content="tblgsn">
<meta property="article:tag" content="C++">
<meta property="article:tag" content="智能指针">
<meta name="twitter:card" content="summary">
<link rel="shortcut icon" href="/images/favicon.ico">
<link rel="icon" type="image/png" href="/images/favicon-192x192.png" sizes="192x192">
<link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png">
<!-- title -->
<title>C++ Smart Pointer(智能指针)</title>
<!-- async scripts -->
<!-- Google Analytics -->
<!-- Umami Analytics -->
<!-- styles -->
<link rel="stylesheet" href="/css/style.css">
<!-- persian styles -->
<!-- rss -->
<link rel="alternate" href="/true" title="tblgsn的个人博客" type="application/atom+xml" />
<!-- mathjax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
skipTags: ['script', 'noscript', 'style', 'textarea', 'pre'],
inlineMath: [['$','$']]
}
});
</script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-MML-AM_CHTML' async></script>
<meta name="generator" content="Hexo 7.0.0"></head>
<body class="max-width mx-auto px3 ltr">
<div id="header-post">
<a id="menu-icon" href="#" aria-label="Menu"><i class="fa-solid fa-bars fa-lg"></i></a>
<a id="menu-icon-tablet" href="#" aria-label="Menu"><i class="fa-solid fa-bars fa-lg"></i></a>
<a id="top-icon-tablet" href="#" aria-label="Top" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');" style="display:none;"><i class="fa-solid fa-chevron-up fa-lg"></i></a>
<span id="menu">
<span id="nav">
<ul>
<!--
--><li><a href="/">Home</a></li><!--
--><!--
--><li><a href="/archives/">Writing</a></li><!--
--><!--
--><li><a target="_blank" rel="noopener" href="http://github.com/tblgsn">Projects</a></li><!--
--><!--
--><li><a href="/about/">About</a></li><!--
-->
</ul>
</span>
<br/>
<span id="actions">
<ul>
<li><a class="icon" aria-label="Previous post" href="/InstallOpencv20201024.html"><i class="fa-solid fa-chevron-left" aria-hidden="true" onmouseover="$('#i-prev').toggle();" onmouseout="$('#i-prev').toggle();"></i></a></li>
<li><a class="icon" aria-label="Next post" href="/InstallPCL20200912.html"><i class="fa-solid fa-chevron-right" aria-hidden="true" onmouseover="$('#i-next').toggle();" onmouseout="$('#i-next').toggle();"></i></a></li>
<li><a class="icon" aria-label="Back to top" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');"><i class="fa-solid fa-chevron-up" aria-hidden="true" onmouseover="$('#i-top').toggle();" onmouseout="$('#i-top').toggle();"></i></a></li>
<li><a class="icon" aria-label="Share post" href="#"><i class="fa-solid fa-share-alt" aria-hidden="true" onmouseover="$('#i-share').toggle();" onmouseout="$('#i-share').toggle();" onclick="$('#share').toggle();return false;"></i></a></li>
</ul>
<span id="i-prev" class="info" style="display:none;">Previous post</span>
<span id="i-next" class="info" style="display:none;">Next post</span>
<span id="i-top" class="info" style="display:none;">Back to top</span>
<span id="i-share" class="info" style="display:none;">Share post</span>
</span>
<br/>
<div id="share" style="display: none">
<ul>
<li><a class="icon" target="_blank" rel="noopener" href="http://www.facebook.com/sharer.php?u=https://tblgsn.github.io/C++SmartPointer20201023.html"><i class="fab fa-facebook " aria-hidden="true"></i></a></li>
<li><a class="icon" target="_blank" rel="noopener" href="https://twitter.com/share?url=https://tblgsn.github.io/C++SmartPointer20201023.html&text=C++ Smart Pointer(智能指针)"><i class="fab fa-twitter " aria-hidden="true"></i></a></li>
<li><a class="icon" target="_blank" rel="noopener" href="http://www.linkedin.com/shareArticle?url=https://tblgsn.github.io/C++SmartPointer20201023.html&title=C++ Smart Pointer(智能指针)"><i class="fab fa-linkedin " aria-hidden="true"></i></a></li>
<li><a class="icon" target="_blank" rel="noopener" href="https://pinterest.com/pin/create/bookmarklet/?url=https://tblgsn.github.io/C++SmartPointer20201023.html&is_video=false&description=C++ Smart Pointer(智能指针)"><i class="fab fa-pinterest " aria-hidden="true"></i></a></li>
<li><a class="icon" href="mailto:?subject=C++ Smart Pointer(智能指针)&body=Check out this article: https://tblgsn.github.io/C++SmartPointer20201023.html"><i class="fa-solid fa-envelope " aria-hidden="true"></i></a></li>
<li><a class="icon" target="_blank" rel="noopener" href="https://getpocket.com/save?url=https://tblgsn.github.io/C++SmartPointer20201023.html&title=C++ Smart Pointer(智能指针)"><i class="fab fa-get-pocket " aria-hidden="true"></i></a></li>
<li><a class="icon" target="_blank" rel="noopener" href="http://reddit.com/submit?url=https://tblgsn.github.io/C++SmartPointer20201023.html&title=C++ Smart Pointer(智能指针)"><i class="fab fa-reddit " aria-hidden="true"></i></a></li>
<li><a class="icon" target="_blank" rel="noopener" href="http://www.stumbleupon.com/submit?url=https://tblgsn.github.io/C++SmartPointer20201023.html&title=C++ Smart Pointer(智能指针)"><i class="fab fa-stumbleupon " aria-hidden="true"></i></a></li>
<li><a class="icon" target="_blank" rel="noopener" href="http://digg.com/submit?url=https://tblgsn.github.io/C++SmartPointer20201023.html&title=C++ Smart Pointer(智能指针)"><i class="fab fa-digg " aria-hidden="true"></i></a></li>
<li><a class="icon" target="_blank" rel="noopener" href="http://www.tumblr.com/share/link?url=https://tblgsn.github.io/C++SmartPointer20201023.html&name=C++ Smart Pointer(智能指针)&description=<p>早在C++98&#x2F;03标准的时候,C++就引入了智能指针(Smart Pointer)的概念来帮助程序员对于堆内存进行自动回收。</p>
<p>引入的目地主要是:对指针的行为进行一定的规范。这有很多的好处,比如:</p>
<ul>
<li>这样可以避免野指针的出现</li>
<li>这样可以避免错误的对于同一块地址进行两次释放</li>
<li>释放不在使用的内存资源,避免内存的泄漏.<br>智能指针使得为我们能够更加安全有效的使用(共享)同一块堆空间."><i class="fab fa-tumblr " aria-hidden="true"></i></a></li>
<li><a class="icon" target="_blank" rel="noopener" href="https://news.ycombinator.com/submitlink?u=https://tblgsn.github.io/C++SmartPointer20201023.html&t=C++ Smart Pointer(智能指针)"><i class="fab fa-hacker-news " aria-hidden="true"></i></a></li>
</ul>
</div>
<div id="toc">
<ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#shared-ptr%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="toc-number">1.</span> <span class="toc-text">shared_ptr的实现</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%E6%99%BA%E8%83%BD%E6%8C%87%E9%92%88"><span class="toc-number">2.</span> <span class="toc-text">如何使用智能指针</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#shared-ptr%E7%9A%84%E6%9E%84%E9%80%A0%E6%96%B9%E6%B3%95"><span class="toc-number">2.1.</span> <span class="toc-text">shared_ptr的构造方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#shared-ptr%E6%99%BA%E8%83%BD%E6%8C%87%E9%92%88%E7%9A%84%E9%87%8A%E6%94%BE%E5%92%8C%E5%86%85%E5%AD%98%E7%9A%84%E9%87%8A%E6%94%BE"><span class="toc-number">2.2.</span> <span class="toc-text">shared_ptr智能指针的释放和内存的释放</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%B6%E4%BB%96%E6%96%B9%E6%B3%95"><span class="toc-number">2.3.</span> <span class="toc-text">其他方法</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#shared-ptr-unique-ptr-std-weak-ptr%E4%B9%8B%E9%97%B4%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-number">3.</span> <span class="toc-text">shared_ptr,unique_ptr, std::weak_ptr之间的区别</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8F%82%E8%80%83"><span class="toc-number">4.</span> <span class="toc-text">参考</span></a></li></ol>
</div>
</span>
</div>
<div class="content index py4 ">
<article class="post h-entry" itemscope itemtype="http://schema.org/BlogPosting">
<header>
<h1 class="posttitle p-name" itemprop="name headline">
C++ Smart Pointer(智能指针)
</h1>
<div class="meta">
<span class="author p-author h-card" itemprop="author" itemscope itemtype="http://schema.org/Person">
<span class="p-name" itemprop="name">@TBLGSn</span>
</span>
<div class="postdate">
<time datetime="2020-10-23T13:35:00.000Z" class="dt-published" itemprop="datePublished">2020-10-23</time>
</div>
<div class="article-tag">
<i class="fa-solid fa-tag"></i>
<a class="p-category" href="/tags/C/" rel="tag">C++</a>, <a class="p-category" href="/tags/%E6%99%BA%E8%83%BD%E6%8C%87%E9%92%88/" rel="tag">智能指针</a>
</div>
</div>
</header>
<div class="content e-content" itemprop="articleBody">
<p>早在C++98/03标准的时候,C++就引入了智能指针(Smart Pointer)的概念来帮助程序员对于堆内存进行自动回收。</p>
<p>引入的目地主要是:对指针的行为进行一定的规范。这有很多的好处,比如:</p>
<ul>
<li>这样可以避免野指针的出现</li>
<li>这样可以避免错误的对于同一块地址进行两次释放</li>
<li>释放不在使用的内存资源,避免内存的泄漏.<br>智能指针使得为我们能够更加安全有效的使用(共享)同一块堆空间.<span id="more"></span></li>
</ul>
<h1 id="shared-ptr的实现"><a href="#shared-ptr的实现" class="headerlink" title="shared_ptr的实现"></a>shared_ptr的实现</h1><p>C++ 智能指针是采用的 引用计数(Reference counting) 的方式实现的。更简单的说,智能指针会负责维护一个整形值用于标记当前空间的引用值。当有新的对象使用同一块堆内存时,整形值加一。当使用该块堆内存的对象被释放掉时,整形值减一。当这个值减少为0时,则表示除了不在会有对象使用这块内存,该堆空间会被释放掉(而不用程序员担心什么时候释放)。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// std::shared_ptr采用的是模板类的方式定义的,它继承自std::_shared_ptr 这个类(shared_ptr_base.h文件中).</span></span><br><span class="line"> <span class="keyword">template</span><<span class="keyword">typename</span> _Tp></span><br><span class="line"> <span class="keyword">class</span> <span class="title class_">shared_ptr</span> : <span class="keyword">public</span> __shared_ptr<_Tp></span><br></pre></td></tr></table></figure>
<p>shared_ptr继承自_shared_ptr,在这个类中维持了两个对象,一个是element_type类型的指针_M_ptr,一个是__weak_count<_Lp>类型的计数器_M_refcount。通过对这两个对象的维护,实现智能指针的目的.<br>例如,use_count()函数借助_M_refcount直接返回的引用数。 </p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">long</span> <span class="title">use_count</span><span class="params">()</span> <span class="type">const</span> <span class="keyword">noexcept</span></span>{ </span><br><span class="line"> <span class="keyword">return</span> _M_refcount._M_get_use_count(); </span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<h1 id="如何使用智能指针"><a href="#如何使用智能指针" class="headerlink" title="如何使用智能指针"></a>如何使用智能指针</h1><p>C++11中提供了三种智能指针:std::shared_ptr, std::unique_ptr, std::weak_ptr,使用时需添加头文件<memory></p>
<blockquote>
<p>C++98/03 标准中,曾经支持使用 auto_ptr 智能指针来实现堆内存的自动回收,但后来在C++17被废除.</p>
</blockquote>
<p>下面以shared_ptr为例,介绍C++中智能指针的使用.</p>
<h2 id="shared-ptr的构造方法"><a href="#shared-ptr的构造方法" class="headerlink" title="shared_ptr的构造方法"></a>shared_ptr的构造方法</h2><p>shared_ptr 这个类为我们提供了十几种创建共享指针的构造方法.</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 我们能够通过以下的方式来创建 shared_ptr 指针</span></span><br><span class="line">std::shared_ptr<<span class="type">int</span>> p1;</span><br><span class="line"><span class="function">std::shared_ptr<<span class="type">int</span>> <span class="title">p1</span><span class="params">(<span class="literal">nullptr</span>)</span></span>;</span><br><span class="line"><span class="function">std::shared_ptr<<span class="type">int</span>> <span class="title">p1</span><span class="params">(<span class="keyword">new</span> <span class="type">int</span>[<span class="number">10</span>])</span></span>;</span><br><span class="line"><span class="comment">//我们还可以借助make_shared<T>函数</span></span><br><span class="line">std::shared_ptr<<span class="type">int</span>> p3 = std::<span class="built_in">make_shared</span><<span class="type">int</span>>(<span class="number">10</span>);</span><br><span class="line"><span class="comment">//拷贝构造函数</span></span><br><span class="line"><span class="function">std::shared_ptr<<span class="type">int</span>> <span class="title">p4</span><span class="params">(p3)</span></span>;</span><br><span class="line">>>运行之后,计数加<span class="number">1</span>,p3 和 p4 指向同一块堆内存.</span><br><span class="line"><span class="comment">//移动构造函数</span></span><br><span class="line"><span class="function">std::shared_ptr<<span class="type">int</span>> <span class="title">p5</span><span class="params">(std::move(p4))</span></span>;</span><br><span class="line">>运行之后,计数不变p5变为指向内存的智能指针,p4变成空智能指针</span><br></pre></td></tr></table></figure>
<h2 id="shared-ptr智能指针的释放和内存的释放"><a href="#shared-ptr智能指针的释放和内存的释放" class="headerlink" title="shared_ptr智能指针的释放和内存的释放"></a>shared_ptr智能指针的释放和内存的释放</h2><p>以下的两种情况会导致内存的释放:</p>
<ul>
<li>最后一个拥有该块堆内存的shared_ptr指针被销毁时.</li>
<li>最后一个拥有该对象的shared_ptr通过操作符=或reset()被分配另一个指针时。</li>
</ul>
<p>智能指针除了为我们提供了默认的内存释放规则,还允许我们自定义内存释放的规则.</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//指定 default_delete 作为释放规则</span></span><br><span class="line"><span class="function">std::shared_ptr<<span class="type">int</span>> <span class="title">p6</span><span class="params">(<span class="keyword">new</span> <span class="type">int</span>[<span class="number">10</span>], std::default_delete<<span class="type">int</span>[]>())</span></span>;</span><br><span class="line"><span class="comment">//自定义释放规则</span></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">deleteInt</span><span class="params">(<span class="type">int</span>*p)</span> </span>{</span><br><span class="line"> <span class="keyword">delete</span> []p;</span><br><span class="line">}</span><br><span class="line"><span class="comment">//初始化智能指针,并自定义释放规则</span></span><br><span class="line"><span class="function">std::shared_ptr<<span class="type">int</span>> <span class="title">p7</span><span class="params">(<span class="keyword">new</span> <span class="type">int</span>[<span class="number">10</span>], deleteInt)</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="function">std::shared_ptr<<span class="type">int</span>> <span class="title">p8</span><span class="params">(<span class="keyword">new</span> <span class="type">int</span>[<span class="number">10</span>],[](<span class="type">int</span>* p){<span class="keyword">delete</span> []p; })</span></span></span><br></pre></td></tr></table></figure>
<h2 id="其他方法"><a href="#其他方法" class="headerlink" title="其他方法"></a>其他方法</h2><p>shared_ptr 是继承的__shared_ptr 这个类.<br>这个基类为我们提供了以下的一些方法:</p>
<table>
<thead>
<tr>
<th align="center">方法名</th>
<th align="center">说明</th>
<th align="center">返回类型</th>
</tr>
</thead>
<tbody><tr>
<td align="center">get()</td>
<td align="center">获得当前智能智能指向元素的普通指针</td>
<td align="center">element_type*</td>
</tr>
<tr>
<td align="center">user_count()</td>
<td align="center">当前堆内存空间的引用量</td>
<td align="center">long</td>
</tr>
<tr>
<td align="center">unique()</td>
<td align="center">当前堆内存是否还有其他引用</td>
<td align="center">bool</td>
</tr>
<tr>
<td align="center">swap()</td>
<td align="center">交换两个智能指针</td>
<td align="center">void</td>
</tr>
<tr>
<td align="center">reset()</td>
<td align="center">没有参数时,当前智能指针变为空智能指针,有参数时当前智能指针指向给定的新内存空间,原内存引用值减1,当前内存引用值置1</td>
<td align="center">void</td>
</tr>
</tbody></table>
<h1 id="shared-ptr-unique-ptr-std-weak-ptr之间的区别"><a href="#shared-ptr-unique-ptr-std-weak-ptr之间的区别" class="headerlink" title="shared_ptr,unique_ptr, std::weak_ptr之间的区别"></a>shared_ptr,unique_ptr, std::weak_ptr之间的区别</h1><p>shared_ptr能够实现多个shared_ptr类型的指针“<strong>共享</strong>”使用同一块堆内存,当有一个指针放弃该堆内存的“使用权”时,也不会影响其他指向该堆内存的shared_ptr空间.只有当引用计算变为0时,才会释放掉这一块堆内存空间.</p>
<p>unique_ptr 通过指针<strong>占有</strong>并管理另一对象,并在 unique_ptr 离开作用域时释放该对象的智能指针。、</p>
<p>std::weak_ptr 用来表示对于std::shared_ptr 管理的对象的<strong>弱引用</strong>. 用来表达<strong>临时所有权</strong>的概念,当某个对象只有存在时才需要被访问,而且随时可能被他人删除时,std::weak_ptr 用来跟踪该对象。此外值得注意的是:weak_ptr 类型指针并不会影响所指堆内存空间的引用计数。 </p>
<h1 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h1><blockquote>
<p><a target="_blank" rel="noopener" href="http://c.biancheng.net/view/7898.html">http://c.biancheng.net/view/7898.html</a><br><a target="_blank" rel="noopener" href="https://en.cppreference.com/w/cpp/memory/shared_ptr">https://en.cppreference.com/w/cpp/memory/shared_ptr</a></p>
</blockquote>
</div>
</article>
<div class="blog-post-comments">
<div id="utterances_thread">
<noscript>Please enable JavaScript to view the comments.</noscript>
</div>
</div>
<div id="footer-post-container">
<div id="footer-post">
<div id="nav-footer" style="display: none">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/archives/">Writing</a></li>
<li><a target="_blank" rel="noopener" href="http://github.com/tblgsn">Projects</a></li>
<li><a href="/about/">About</a></li>
</ul>
</div>
<div id="toc-footer" style="display: none">
<ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#shared-ptr%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="toc-number">1.</span> <span class="toc-text">shared_ptr的实现</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%E6%99%BA%E8%83%BD%E6%8C%87%E9%92%88"><span class="toc-number">2.</span> <span class="toc-text">如何使用智能指针</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#shared-ptr%E7%9A%84%E6%9E%84%E9%80%A0%E6%96%B9%E6%B3%95"><span class="toc-number">2.1.</span> <span class="toc-text">shared_ptr的构造方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#shared-ptr%E6%99%BA%E8%83%BD%E6%8C%87%E9%92%88%E7%9A%84%E9%87%8A%E6%94%BE%E5%92%8C%E5%86%85%E5%AD%98%E7%9A%84%E9%87%8A%E6%94%BE"><span class="toc-number">2.2.</span> <span class="toc-text">shared_ptr智能指针的释放和内存的释放</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%B6%E4%BB%96%E6%96%B9%E6%B3%95"><span class="toc-number">2.3.</span> <span class="toc-text">其他方法</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#shared-ptr-unique-ptr-std-weak-ptr%E4%B9%8B%E9%97%B4%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-number">3.</span> <span class="toc-text">shared_ptr,unique_ptr, std::weak_ptr之间的区别</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8F%82%E8%80%83"><span class="toc-number">4.</span> <span class="toc-text">参考</span></a></li></ol>
</div>
<div id="share-footer" style="display: none">
<ul>
<li><a class="icon" target="_blank" rel="noopener" href="http://www.facebook.com/sharer.php?u=https://tblgsn.github.io/C++SmartPointer20201023.html"><i class="fab fa-facebook fa-lg" aria-hidden="true"></i></a></li>
<li><a class="icon" target="_blank" rel="noopener" href="https://twitter.com/share?url=https://tblgsn.github.io/C++SmartPointer20201023.html&text=C++ Smart Pointer(智能指针)"><i class="fab fa-twitter fa-lg" aria-hidden="true"></i></a></li>
<li><a class="icon" target="_blank" rel="noopener" href="http://www.linkedin.com/shareArticle?url=https://tblgsn.github.io/C++SmartPointer20201023.html&title=C++ Smart Pointer(智能指针)"><i class="fab fa-linkedin fa-lg" aria-hidden="true"></i></a></li>
<li><a class="icon" target="_blank" rel="noopener" href="https://pinterest.com/pin/create/bookmarklet/?url=https://tblgsn.github.io/C++SmartPointer20201023.html&is_video=false&description=C++ Smart Pointer(智能指针)"><i class="fab fa-pinterest fa-lg" aria-hidden="true"></i></a></li>
<li><a class="icon" href="mailto:?subject=C++ Smart Pointer(智能指针)&body=Check out this article: https://tblgsn.github.io/C++SmartPointer20201023.html"><i class="fa-solid fa-envelope fa-lg" aria-hidden="true"></i></a></li>
<li><a class="icon" target="_blank" rel="noopener" href="https://getpocket.com/save?url=https://tblgsn.github.io/C++SmartPointer20201023.html&title=C++ Smart Pointer(智能指针)"><i class="fab fa-get-pocket fa-lg" aria-hidden="true"></i></a></li>
<li><a class="icon" target="_blank" rel="noopener" href="http://reddit.com/submit?url=https://tblgsn.github.io/C++SmartPointer20201023.html&title=C++ Smart Pointer(智能指针)"><i class="fab fa-reddit fa-lg" aria-hidden="true"></i></a></li>
<li><a class="icon" target="_blank" rel="noopener" href="http://www.stumbleupon.com/submit?url=https://tblgsn.github.io/C++SmartPointer20201023.html&title=C++ Smart Pointer(智能指针)"><i class="fab fa-stumbleupon fa-lg" aria-hidden="true"></i></a></li>
<li><a class="icon" target="_blank" rel="noopener" href="http://digg.com/submit?url=https://tblgsn.github.io/C++SmartPointer20201023.html&title=C++ Smart Pointer(智能指针)"><i class="fab fa-digg fa-lg" aria-hidden="true"></i></a></li>
<li><a class="icon" target="_blank" rel="noopener" href="http://www.tumblr.com/share/link?url=https://tblgsn.github.io/C++SmartPointer20201023.html&name=C++ Smart Pointer(智能指针)&description=<p>早在C++98&#x2F;03标准的时候,C++就引入了智能指针(Smart Pointer)的概念来帮助程序员对于堆内存进行自动回收。</p>
<p>引入的目地主要是:对指针的行为进行一定的规范。这有很多的好处,比如:</p>
<ul>
<li>这样可以避免野指针的出现</li>
<li>这样可以避免错误的对于同一块地址进行两次释放</li>
<li>释放不在使用的内存资源,避免内存的泄漏.<br>智能指针使得为我们能够更加安全有效的使用(共享)同一块堆空间."><i class="fab fa-tumblr fa-lg" aria-hidden="true"></i></a></li>
<li><a class="icon" target="_blank" rel="noopener" href="https://news.ycombinator.com/submitlink?u=https://tblgsn.github.io/C++SmartPointer20201023.html&t=C++ Smart Pointer(智能指针)"><i class="fab fa-hacker-news fa-lg" aria-hidden="true"></i></a></li>
</ul>
</div>
<div id="actions-footer">
<a id="menu" class="icon" href="#" onclick="$('#nav-footer').toggle();return false;"><i class="fa-solid fa-bars fa-lg" aria-hidden="true"></i> Menu</a>
<a id="toc" class="icon" href="#" onclick="$('#toc-footer').toggle();return false;"><i class="fa-solid fa-list fa-lg" aria-hidden="true"></i> TOC</a>
<a id="share" class="icon" href="#" onclick="$('#share-footer').toggle();return false;"><i class="fa-solid fa-share-alt fa-lg" aria-hidden="true"></i> Share</a>
<a id="top" style="display:none" class="icon" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');"><i class="fa-solid fa-chevron-up fa-lg" aria-hidden="true"></i> Top</a>
</div>
</div>
</div>
<footer id="footer">
<div class="footer-left">
Copyright ©
2019-2025
tblgsn
</div>
<div class="footer-right">
<nav>
<ul>
<!--
--><li><a href="/">Home</a></li><!--
--><!--
--><li><a href="/archives/">Writing</a></li><!--
--><!--
--><li><a target="_blank" rel="noopener" href="http://github.com/tblgsn">Projects</a></li><!--
--><!--
--><li><a href="/about/">About</a></li><!--
-->
</ul>
</nav>
</div>
</footer>
</div>
<!-- styles -->
<link rel="preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" crossorigin="anonymous" onload="this.onload=null;this.rel='stylesheet'"/>
<!-- jquery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" crossorigin="anonymous"></script>
<!-- clipboard -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.7/clipboard.min.js" crossorigin="anonymous"></script>
<script type="text/javascript">
$(function() {
// copy-btn HTML
var btn = "<span class=\"btn-copy tooltipped tooltipped-sw\" aria-label=\"Copy to clipboard!\">";
btn += '<i class="fa-regular fa-clone"></i>';
btn += '</span>';
// mount it!
$(".highlight table").before(btn);
var clip = new ClipboardJS('.btn-copy', {
text: function(trigger) {
return Array.from(trigger.nextElementSibling.querySelectorAll('.code')).reduce((str,it)=>str+it.innerText+'\n','')
}
});
clip.on('success', function(e) {
e.trigger.setAttribute('aria-label', "Copied!");
e.clearSelection();
})
})
</script>
<script src="/js/main.js"></script>
<!-- search -->
<!-- Baidu Analytics -->
<!-- Cloudflare Analytics -->
<!-- Disqus Comments -->
<!-- utterances Comments -->
<script type="text/javascript">
var utterances_repo = 'TBLGSn/tblgsn.github.io';
var utterances_issue_term = 'url';
var utterances_label = 'Comment';
var utterances_theme = 'github-dark';
(function(){
var script = document.createElement('script');
script.src = 'https://utteranc.es/client.js';
script.setAttribute('repo', utterances_repo);
script.setAttribute('issue-term', 'pathname');
script.setAttribute('label', utterances_label);
script.setAttribute('theme', utterances_theme);
script.setAttribute('crossorigin', 'anonymous');
script.async = true;
(document.getElementById('utterances_thread')).appendChild(script);
}());
</script>
</body>
</html>