C++智能指针模板应用详细介绍

从比较简单的层面来看,智能指针是RAII(Resource Acquisition Is Initialization,资源获取即初始化)机制对普通指针进行的一层封装。这样使得智能指针的行为动作像一个指针,本质上却是一个对象,这样可以方便管理一个对象的生命周期

智能指针模板类

void remodel(std::string & str) { std::string *ps =new std::string(str); .... if(oh_no) throw exception(); ... delete ps; return; }

如果上面这段函数出现异常,那么就会发生内存泄漏。传统指针在执行动态内存分配时具有缺陷,很容易导致内存泄漏。如果有一个指针,指针被释放的同时,它指向的内存也能被释放,那就完美了。这种指针就是智能指针。

我们只介绍3个智能指针模板类:auto_ptrunique_ptrshared_ptr,顺便会提一下weak_ptr。其中auto_ptr已经被抛弃了,它是一个过时的产物,我们介绍它只为抛砖引玉。

使用智能指针

这些智能指针模板定义了类似指针的对象,我们把new获得的地址赋给这种对象,当智能指针过期时,它的析构函数会自动释放动态内存。

必须包含头文件memory,这个文件包含模板定义。我们使用模板实例化来创建所需指针.

类模板大概是:

template class auto_ptr { public: explicit auto_ptr(X* p) noexcept; .... } 

所以我们实例化:

auto_ptr pd(new double);或者auto_ptr ps(new string);

对于其他两种智能指针也是一样的构造语法。

//智能指针1.cpp #include #include #include class Report { private: std::string str; public: Report(const std::string &s):str(s){std::cout<<"Object created!\n";} ~Report(){std::cout<<"Object deleted";} void comment() const{std::cout< ps(new Report("using auto_ptr")); ps->comment(); } { std::unique_ptr ps(new Report("using unique_ptr")); ps->comment(); } { std::shared_ptr ps(new Report("using shared_ptr")); ps->comment(); } }

Object created!
using auto_ptr
Object deletedObject created!
using unique_ptr
Object deletedObject created!
using shared_ptr
Object deleted

注意,所有智能指针类都有一个explicit构造函数,该构造函数将指针作为参数。所以它不会将指针转换成智能指针对象。

shared_ptr pd; double *p_reg=new double; pd=p_reg;//不允许因为构造函数是`explicit`修饰的,所以不能隐式类型转换 pd=shared_ptr(p_reg);//允许,使用赋值运算符 shared_ptr pshared=p_reg;//不允许,因为不能隐式类型转换 shared_ptr pshared(p_reg);//允许调用构造函数。 

智能指针和传统指针有很多类似的语法:例如可以使用*ps来解除引用,也可以使用ps->来访问结构成员。

但是最重要的不同是:我们只能用能进行delete或者delete[]的指针来构造智能指针。

也就是说:

int a=5; int *p=&a; shared_ptr ps(p); 

上面这段代码就是错误的,因为p无法使用delete.

#include #include int main() { using namespace std; /*{ auto_ptr ps(new int[2]{1,2}); cout< ps(new int[2]{1,2}); cout< ps(new int[2]{1,2}); cout<

上面代码告诉我们,我们可以使用这样实例化模板,这是为了模拟动态数组。

关于智能指针的注意事项

auto_ptr ps(new string("I reigned lonely as a cloud.")); auto_ptr pd; pd=ps; 

上面这段代码不会报错,但是你可能会问:pd和ps都是智能指针,如果我们把ps赋给pd;那么就说明这两个指针指向同一个string对象,那么当这两个指针消失时,会对同一个string对象释放两次?

我们看看我们如何避免这种问题:

  • 进行深复制
  • 建立所有权概念,对于特定的对象,只能有一个智能指针拥有它,这样就只有拥有它的智能指针的析构函数才会释放内存。然后赋值运算会转让所有权。auto_ptrunique_ptr都是使用这种策略,但是unique_ptr更严格。
  • 使用引用计数,每个对象都会记录有多少个智能指针指向它,然后赋值运算时,计数加1,指针过期时计数减1。当最后一个指针过期时,才会调用delete,这是shared_ptr的策略。

实际上,上述这些策略也适用于复制构造函数。

实际上,unique_ptr就是"唯一指针",指针和被指向的对象一一对应,而shared_ptr就是"分享指针",它允许多个指针指向同一个对象。所以说,shared_ptr的用法更像C风格指针。

我们看上面的代码,pd=ps后,由于string对象的所有权交给了pd,所以*ps就无法使用了。

//智能指针3.cpp #include #include #include int main() { using namespace std; auto_ptr films[5]= { auto_ptr(new string("1")), auto_ptr(new string("2")), auto_ptr(new string("3")), auto_ptr(new string("4")), auto_ptr(new string("5")) }; auto_ptr p; p=films[2]; for(int i=0;i<5;i++) { cout<<*films[i]<

上面这段代码会出错,因为p=films[2];使得,films[2]的所有权转让给p了,所以cout<<*film[2]就会出错。但是如果使用shared_ptr代替auto_ptr就可以正常运行了。如果使用unique_ptr呢?程序会在编译阶段报错,而不是在运行阶段报错,所以说unique_ptr更加严格。

unique_ptr优于auto_ptr

首先就是上面谈过的,unique_ptr的所有权概念比auto_ptr要严格,所以unique_ptr更加安全。

unique_ptr ps(new string("I reigned lonely as a cloud.")); unique_ptr pd; pd=ps; 

上述代码会在编译阶段报错,因为出现了危险的悬挂指针ps(即野指针,指针指向被删除的内存,如果使用野指针修改内存是会造成严重后果)。

但是有时候将一个智能指针赋给另一个并不会留下悬挂指针:

unique_ptr demo(const char*s) { unique_ptr temp(new string(s)); return temp; } ... unique_ptrps; ps= demo("something"); ... 

demo()函数返回一个临时变量temp,然后临时变量temp被赋给ps,那么temp就变成悬挂指针了,但是我们知道ps=demo("something")一旦运行结束,demo()里的所有局部变量都会消失包括temp。所以即使temp是野指针,我们也不会使用它。神奇的是,编译器也允许上面这种赋值。

总之,程序试图将一个unique_ptr赋给另一个时,如果源unique_ptr是个临时右值,编译器允许这么做;如果源unique_ptr会存在一段世界,编译器禁止这么做。

unique_ptr pu1; pu1=unique_ptr(new string("yo!")); 

上面这段代码也是允许的,因为unique_ptr(new string("yo!"))是一个临时右值(右值都是临时的,右值只在当前语句有效,语句结束后右值就会消失)

unique_ptr ps(new string("I reigned lonely as a cloud.")); unique_ptr pd; pd=std::move(ps); 

上面代码是正确的,如果你想要进行将unique_ptr左值,赋给unique_ptr左值,那么你必须使用move()函数,这个函数会将左值转换成右值。

以上所说,反映了一个事实:unique_ptrauto_ptr安全。其实unique_ptr还有一个优点:auto_ptr的析构函数只能使用delete,而unique_ptr的析构函数可以使用delete[]delete

选择智能指针

首先明确一个事实:shared_ptr更方便;unique_ptr更安全。

如果程序需要适用多个指向同一个对象的指针,那么只能选择shared_ptr;如果不需要多个指向同一个对象的指针,那么两种指针都可以使用。总之,嫌麻烦的话就全部用shared_ptr.

#include #include #include #include #include std::unique_ptr make_int(int n) { return std::unique_ptr(new int(n)); } void show(const std::unique_ptr &pi) { std::cout<<*pi<<' '; } int main() { using std::vector; using std::unique_ptr; using std::rand; int size=10; vector> vp(size); for(int i=0;i

上面这段代码是使用unique_ptr写的,#1.#2是没有问题的,因为函数返回值是临时右值,#3就要注意了.show()函数使用的是引用参数,如果换成按值传递,那就会出错,因为这会导致,使用unique_ptr左值初始化pi,这时不允许的,记得吗?在使用unique_ptr时,它的赋值运算符要求:只能用右值赋给左值。(实际上,它的复制构造函数也要求只接受右值)。

unique_ptr是右值的时候,我们可以把他赋给shared_ptr

shared_ptr包含一个显式构造函数,他会把右值unique_ptr转换成shared_ptr:

unique_ptr pup(make_int(rand()%1000));//ok shared_ptr spp(pup);//不允许,构造函数不能接受`unique_ptr`的左值 shared_ptr spr(make_int(rand()%1000));//ok 

weak_ptr

weak_ptr正如它名字所言:一个虚弱的指针,一个不像是指的指针。weak_ptr是用来辅助shared_ptr的。

为什么说weak_ptr不像指针呢?是因为它没有重载*[]运算符。

通常,我们使用shared_ptr来初始化weak_ptr,那么这两个指针都指向是同一块动态内存。

weak_ptrshared_ptr的辅助,所以它帮忙能查看这块动态内存的信息:包括引用计数、存的信息。

#include #include int main() { using std::shared_ptr; using std::weak_ptr; using std::cout; using std::endl; shared_ptr p1(new int(255)); weak_ptrwp(p1); cout<<"引用计数: "< p2=p1; cout<<"引用计数: "<

引用计数: 1  
存储信息: 255
引用计数: 2  
存储信息: 255

weak_ptr的类方法中use_count()查看指向和当前weak_ptr指针相同的shared_ptr指针的数量,lock()函数返回一个和当前weak_ptr指针指向相同的shared_ptr指针。

到此这篇关于C++智能指针模板应用详细介绍的文章就介绍到这了,更多相关C++智能指针内容请搜索0133技术站以前的文章或继续浏览下面的相关文章希望大家以后多多支持0133技术站!

以上就是C++智能指针模板应用详细介绍的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » C语言