首页 > 其他 > 详细

动态内存 与 智能指针

时间:2020-06-10 21:04:14      阅读:42      评论:0      收藏:0      [点我收藏+]

 参考https://www.cnblogs.com/lanxuezaipiao/p/4132096.html#top 与c++ primer第五版(p432)

1.动态内存与智能指针

  • 智能指针包含在头文件<memory>中,shared_ptr、unique_ptr、weak_ptr。
  • 智能指针与普通指针区别在于,它负责自动释放所指向的对象。
  • shared_ptr 允许多个指针指向同一个对象,unique_ptr 则独占所指向的对象,二者管理底层指针的方式不同。
  • 智能指针类似于vector,也是模板

   程序使用动态内存的三个原因:

  1. 程序不知道自己需要使用多少个元素;例如容器类
  2. 程序不知道所需对象的准确类型; 15章涉及
  3. 程序需要在多个对象之间共享数据。

2.share_ptr

2.1 make_shared函数

  此函数在动态内存中分配一个对象并初始化,返回指向该对象的shared_ptr

技术分享图片
//指向了一个值为42的int的shared_ptr
shared_ptr<int> p3 = make_shared<int>42;
//传递的参数必须与string的某个构造函数相匹配
shared_ptr<string>p4=make_shared<string>(10,9);
View Code

2.2 shared_ptr的拷贝与赋值

  每一个shared_int都关联一个计数器,称为引用计数。

   一旦计数器为0,会自动释放所管理的对象,即shared_ptr的析构函数销毁对象,释放其内存。

auto r = make_shared<int>(42);
r = p; //给r赋值,递减r原来指向对象的引用计数

2.3 使用动态生存期的类

我们使用的类中,分配的资源与使用的对象的生存周期一致;如下:

vector<int> v1;
{
    vector<int> v2={1,2};
    v1=v2;
} //v2和它的元素均被销毁;
   // v1中有三个元素,是v2 的拷贝

但某些类分配的资源与使用的对象的生存周期相互独立

Blob<string> b1;
{//新作用域
    Blob<string> b2={"1","1"};
    b1=b2;
}//b2被销毁,但b2中的元素不能销毁

 StrBlob是一个管理string的类,借助标准库容器vector,以及动态内存管理类shared_ptr,我们将vector保存在动态内存里,这样就能在多个对象之间共享内存。

技术分享图片
 1 #include <vector>
 2 #include <string>
 3 #include <memory>
 4 class StrBlob
 5 {
 6 public:
 7     typedef std::vector<std::string>::size_type size_type;
 8     StrBlob();
 9     StrBlob(std::initializer_list<std::string> il);
10     size_type size() const {return data->size();}
11     bool empty() const {return data->empty();};
12     //添加和删除元素
13     void push_back(const std::string& t) { data->push_back(t);};
14     void pop_back();
15     //元素访问
16     std::string& front();
17     std::string& back();
18 private:
19     std::shared_ptr<std::vector<std::string>> data;
20     //data[i]不合法时,抛出异常
21     void check(size_type i, const std::string &msg) const;
22 };
View Code

 

技术分享图片
 1 #include "StrBlob.h"
 2 #include <exception>
 3  
 4 StrBlob::StrBlob():data(std::make_shared<std::vector<std::string>>()){}
 5  
 6 StrBlob::StrBlob(std::initializer_list<std::string> il):
 7     data(std::make_shared<std::vector<std::string>>(il)){}
 8  
 9 void StrBlob::check(size_type i, const std::string &msg) const
10 {
11     if(i >= data->size())
12         throw std::out_of_range(msg);
13 }
14  
15 std::string& StrBlob::front()
16 {
17     check(0, "front on empty StrBlob");
18     return data->front();
19 }
20  
21 std::string& StrBlob::back()
22 {
23     check(0, "back on empty StrBlob");
24     return data->back();
25 }
26  
27 void StrBlob::pop_back()
28 {
29     check(0, "pop_back on empty StrBlob");
30     return data->pop_back();
31 }
View Code

 

 

 

 

动态内存 与 智能指针

原文:https://www.cnblogs.com/wsl96/p/13088201.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!