码迷,mamicode.com
首页 > 编程语言 > 详细

C++学习之路: 智能指针入门

时间:2014-10-10 03:17:04      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   sp   div   art   

引言: 编写智能指针的要点:
a) 构造函数接收堆内存
b) 析构函数释放内存
c) 必要时要禁止值语义。
d) 重载*与->两个操作符

 

 1 #ifndef START_PTR_H
 2 #define START_PTR_H
 3 
 4 #include <iostream>
 5 using namespace std;
 6 
 7 class Animal 
 8 {
 9     public:
10         Animal() { cout << "Animal" << endl ;}
11         ~Animal() { cout << "~Animal" << endl; }
12 
13         void run() { cout << "Animal is running....." << endl; }
14 
15 }; 
16 
17 
18 
19 
20 class SmartPtr
21 {
22     public:
23         SmartPtr(Animal * ptr = NULL)  //采用缺省函数
24             :ptr_(ptr) 
25         {
26              
27         }
28 
29         ~SmartPtr()
30         {
31             delete ptr_ ;
32         }
33 
34         Animal &operator*()   //需要重载一个const 版本,否则const SmartPtr 无法解引用
35         {
36             return *ptr_ ;
37         }
38         const Animal &operator*() const
39         {
40             return *ptr_ ;
41         }
42 
43         Animal *operator->()
44         {
45             return ptr_ ;
46         }
47         const Animal *operator->() const
48         {
49             return ptr_ ;
50         }
51     private:
52         SmartPtr(const SmartPtr &other)
53             :ptr_(other.ptr_)
54         {
55             
56         }
57         SmartPtr &operator=(const SmartPtr &other) 
58         {
59             if(this != &other)
60             {
61                 ptr_ = other.ptr_ ;
62             }
63             return *this ;
64         }
65 
66         Animal *ptr_ ;
67 } ;
68 
69 #endif  /*START_PTR_H*/

 

测试代码:

 1 #include "smartPtr.h"
 2 #include <iostream>
 3 using namespace std;
 4 
 5 int main(int argc, const char *argv[])
 6 {
 7     {
 8         SmartPtr ptr(new Animal) ;      //这个智能指针的生命周期仅限于这个花括号内部, 那么它  持有的对象  的生命  也只存在于这对括号中
 9         ptr->run() ;                    //因为智能指针的构造函数中对持有对象进行定义,  在智能指针析构 函数中对持有对象进行释放, 实现自动化管理获取的资源
10     }
11     return 0;
12 }
Animal
Animal is running.....
~Animal

打印结果, 智能指针实现了内存的自动管理

 

总结:

其实

智能指针是个类对象,但是行为表现的像一个指针。它有三种操作符

a)      . 调用的是智能指针这个对象本身的方法。

b)     * 调用的是  解引用出持有的对象

c)      -> 调用的是 调用持有对象内部的成员

 

C++学习之路: 智能指针入门

标签:style   blog   color   io   os   ar   sp   div   art   

原文地址:http://www.cnblogs.com/DLzhang/p/4014811.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!