青青草原综合久久大伊人导航_色综合久久天天综合_日日噜噜夜夜狠狠久久丁香五月_热久久这里只有精品

隨筆 - 55  文章 - 15  trackbacks - 0
<2013年1月>
303112345
6789101112
13141516171819
20212223242526
272829303112
3456789

常用鏈接

留言簿

隨筆分類

隨筆檔案

搜索

  •  

最新評論

閱讀排行榜

評論排行榜

PS:本文為轉(zhuǎn)載。鏈接地址:http://www.codeproject.com/Articles/15351/Implementing-a-simple-smart-pointer-in-c 

Introduction

What are smart pointers? The answer is fairly simple; a smart pointer is a pointer which is smart. What does that mean? Actually, smart pointers are objects which behave like pointers but do more than a pointer. These objects are flexible as pointers and have the advantage of being an object (like constructor and destructors called automatically). A smart pointer is designed to handle the problems caused by using normal pointers (hence calledsmart).

Problems with pointers

What are the common problems we face in C++ programs while using pointers? The answer is memory management. Have a look at the following code:

 Collapse | Copy Code
char* pName  = new char[1024]; … SetName(pName); … … if(null != pName) {        delete[] pName;  }

How many times have we found a bug which was caused because we forgot to delete pName. It would be great if someone could take care of releasing the memory when the pointer is not useful (we are not talking about the garbage collector here). What if the pointer itself takes care of that? Yes, that’s exactly what smart pointers are intended to do. Let us write a smart pointer and see how we can handle a pointer better.

We shall start with a realistic example. Let’s say we have a class called Person which is defined as below.

 Collapse | Copy Code
class Person {     int age;     char* pName;      public:         Person(): pName(0),age(0)         {         }         Person(char* pName, int age): pName(pName), age(age)         {         }         ~Person()         {         }          void Display()         {             printf("Name = %s Age = %d \n", pName, age);         }         void Shout()         {             printf("Ooooooooooooooooo",);         }  };

Now we shall write the client code to use Person.

 Collapse | Copy Code
void main() {     Person* pPerson  = new Person("Scott", 25);     pPerson->Display();     delete pPerson; }

Now look at this code, every time I create a pointer, I need to take care of deleting it. This is exactly what I want to avoid. I need some automatic mechanism which deletes the pointer. One thing which strikes to me is a destructor. But pointers do not have destructors, so what? Our smart pointer can have one. So we will create a class calledSP which can hold a pointer to the Person class and will delete the pointer when its destructor is called. Hence my client code will change to something like this:

 Collapse | Copy Code
void main() {     SP p(new Person("Scott", 25));     p->Display();     // Dont need to delete Person pointer.. }

Note the following things:

  • We have created an object of class SP which holds our Person class pointer. Since the destructor of the SPclass will be called when this object goes out of scope, it will delete the Person class pointer (as its main responsibility); hence we don’t have the pain of deleting the pointer.
  • One more thing of major importance is that we should be able to call the Display method using the SP class object the way we used to call using the Person class pointer, i.e., the class should behave exactly like apointer.

Interface for a smart pointer

Since the smart pointer should behave like a pointer, it should support the same interface as pointers do; i.e., they should support the following operations.

  • Dereferencing (operator *)
  • Indirection (operator ->)

Let us write the SP class now.

 Collapse | Copy Code
class SP { private:     Person*    pData; // pointer to person class public:     SP(Person* pValue) : pData(pValue)     {     }     ~SP()     {         // pointer no longer requried         delete pData;     }      Person& operator* ()     {         return *pData;     }      Person* operator-> ()     {             return pData;     } };

This class is our smart pointer class. The main responsibility of this class is to hold a pointer to the Person class and then delete it when its destructor is called. It should also support the interface of the pointer.

Generic smart pointer class

One problem which we see here is that we can use this smart pointer class for a pointer of the Person class only. This means that we have to create a smart pointer class for each type, and that’s not easy. We can solve this problem by making use of templates and making this smart pointer class generic. So let us change the code like this:

 Collapse | Copy Code
template < typename T > class SP {     private:     T*    pData; // Generic pointer to be stored     public:     SP(T* pValue) : pData(pValue)     {     }     ~SP()     {         delete pData;     }      T& operator* ()     {         return *pData;     }      T* operator-> ()     {         return pData;     } };  void main() {     SP<PERSON> p(new Person("Scott", 25));     p->Display();     // Dont need to delete Person pointer.. }

Now we can use our smart pointer class for any type of pointer. So is our smart pointer really smart? Check the following code segment.

 Collapse | Copy Code
void main() {     SP<PERSON> p(new Person("Scott", 25));     p->Display();     {         SP<PERSON> q = p;         q->Display();         // Destructor of Q will be called here..     }     p->Display(); }

Look what happens here. p and q are referring to the same Person class pointer. Now when q goes out of scope, the destructor of q will be called which deletes the Person class pointer. Now we cannot call p->Display();since p will be left with a dangling pointer and this call will fail. (Note that this problem would have existed even if we were using normal pointers instead of smart pointers.) We should not delete the Person class pointer unless no body is using it. How do we do that? Implementing a reference counting mechanism in our smart pointer class will solve this problem.

Reference counting

What we are going to do is we will have a reference counting class RC. This class will maintain an integer value which represents the reference count. We will have methods to increment and decrement the reference count.

 Collapse | Copy Code
class RC {     private:     int count; // Reference count      public:     void AddRef()     {         // Increment the reference count         count++;     }      int Release()     {         // Decrement the reference count and         // return the reference count.         return --count;     } };

Now that we have a reference counting class, we will introduce this to our smart pointer class. We will maintain apointer to class RC in our SP class and this pointer will be shared for all instances of the smart pointer which refers to the same pointer. For this to happen, we need to have an assignment operator and copy constructor in ourSP class.

 Collapse | Copy Code
template < typename T > class SP { private:     T*    pData;       // pointer     RC* reference; // Reference count  public:     SP() : pData(0), reference(0)      {         // Create a new reference          reference = new RC();         // Increment the reference count         reference->AddRef();     }      SP(T* pValue) : pData(pValue), reference(0)     {         // Create a new reference          reference = new RC();         // Increment the reference count         reference->AddRef();     }      SP(const SP<T>& sp) : pData(sp.pData), reference(sp.reference)     {         // Copy constructor         // Copy the data and reference pointer         // and increment the reference count         reference->AddRef();     }      ~SP()     {         // Destructor         // Decrement the reference count         // if reference become zero delete the data         if(reference->Release() == 0)         {             delete pData;             delete reference;         }     }      T& operator* ()     {         return *pData;     }      T* operator-> ()     {         return pData;     }          SP<T>& operator = (const SP<T>& sp)     {         // Assignment operator         if (this != &sp) // Avoid self assignment         {             // Decrement the old reference count             // if reference become zero delete the old data             if(reference->Release() == 0)             {                 delete pData;                 delete reference;             }              // Copy the data and reference pointer             // and increment the reference count             pData = sp.pData;             reference = sp.reference;             reference->AddRef();         }         return *this;     } };

Let us have a look at the client code.

 Collapse | Copy Code
void main() {     SP<PERSON> p(new Person("Scott", 25));     p->Display();     {         SP<PERSON> q = p;         q->Display();         // Destructor of q will be called here..          SP<PERSON> r;         r = p;         r->Display();         // Destructor of r will be called here..     }     p->Display();     // Destructor of p will be called here      // and person pointer will be deleted }

When we create a smart pointer p of type Person, the constructor of SP will be called, the data will be stored, and a new RC pointer will be created. The AddRef method of RC is called to increment the reference count to 1. Now SP q = p; will create a new smart pointer q using the copy constructor. Here the data will be copied and the reference will again be incremented to 2. Now r = p; will call the assignment operator to assign the value of p to q. Here also we copy the data and increment the reference count, thus making the count 3. When r and q go out of scope, the destructors of the respective objects will be called. Here the reference count will be decremented, but data will not be deleted unless the reference count becomes zero. This happens only when the destructor of p is called. Hence our data will be deleted only when no body is referring to it.

Applications

Memory leaks: Using smart pointers reduces the work of managing pointers for memory leaks. Now you could create a pointer and forget about deleting it, the smart pointer will do that for you. This is the simplest garbage collector we could think of.

Exceptions: Smart pointers are very useful where exceptions are used. For example, look at the following code:

 Collapse | Copy Code
void MakeNoise() {     Person* p = new Person("Scott", 25);     p->Shout();     delete p; }

We are using a normal pointer here and deleting it after using, so every thing looks okay here. But what if our Shoutfunction throws some exception? delete p; will never be called. So we have a memory leak. Let us handle that.

 Collapse | Copy Code
void MakeNoise() {     Person* p = new Person("Scott", 25);     try     {         p->Shout();     }     catch(...)     {         delete p;         throw;     }     delete p; }

Don't you think this is an overhead of catching an exception and re-throwing it? This code becomes cumbersome if you have many pointers created. How will a smart pointer help here? Let's have a look at the same code if a smartpointer is used.

 Collapse | Copy Code
void MakeNoise() {     SP<Person> p(new Person("Scott", 25));     p->Shout(); }

We are making use of a smart pointer here; yes, we don’t need to catch the exception here. If the Shout method throws an exception, stack unwinding will happen for the function and during this, the destructor of all local objects will be called, hence the destructor of p will be called which will release the memory, hence we are safe. So this makes it very useful to use smart pointers here.

Conclusion

Smart pointers are useful for writing safe and efficient code in C++. Make use of smart pointers and take the advantage of garbage collection. Take a look at Scott Meyers' auto_ptr implementation in STL.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

posted on 2012-05-18 16:36 Dino-Tech 閱讀(222) 評論(0)  編輯 收藏 引用

只有注冊用戶登錄后才能發(fā)表評論。
網(wǎng)站導(dǎo)航: 博客園   IT新聞   BlogJava   博問   Chat2DB   管理


青青草原综合久久大伊人导航_色综合久久天天综合_日日噜噜夜夜狠狠久久丁香五月_热久久这里只有精品
  • <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>
            欧美一级日韩一级| 亚洲一区二区精品视频| 亚洲黄色毛片| 蜜桃精品一区二区三区 | 99视频精品| 99国产精品99久久久久久| 在线亚洲一区| 欧美在线一二三| 久久在线免费| 欧美美女福利视频| 国产欧美日韩一区二区三区| 韩国一区二区在线观看| 亚洲精品国产精品国产自| 亚洲在线播放| 欧美 日韩 国产一区二区在线视频| 欧美国产日韩在线| 一区二区三区日韩| 久久亚洲精品伦理| 国产精品video| 在线观看欧美激情| 亚洲一区在线视频| 欧美国产日韩一二三区| 亚洲欧美日本另类| 欧美精品一区三区在线观看| 韩国av一区二区三区四区| 在线视频你懂得一区二区三区| 久久精品夜夜夜夜久久| 亚洲精品乱码久久久久久按摩观| 亚洲图色在线| 欧美国产亚洲精品久久久8v| 国产一区二区三区高清| 亚洲自拍另类| 亚洲精品一二三区| 久久综合久久综合这里只有精品| 国产伦精品一区二区三区照片91| 日韩午夜一区| 欧美 日韩 国产一区二区在线视频| 亚洲一区二区三区涩| 欧美日韩国产影片| 亚洲日韩成人| 欧美成人精品激情在线观看| 午夜一区二区三视频在线观看| 欧美日韩一区二区三区在线看 | 欧美一级大片在线免费观看| 亚欧美中日韩视频| 欧美国产免费| 亚洲欧洲一区二区三区| 久久这里只有精品视频首页| 亚洲一区二区三区视频| 欧美性大战久久久久久久| 亚洲乱码国产乱码精品精98午夜 | 久久婷婷综合激情| 久久综合久久美利坚合众国| 女同一区二区| 久久九九免费| 精品999在线观看| 久久综合999| 久久亚洲春色中文字幕| 在线看成人片| 亚洲第一色在线| 米奇777在线欧美播放| 亚洲国产精品久久久久婷婷老年 | 午夜精品影院在线观看| 国产欧美一区二区三区视频 | 亚洲电影免费观看高清完整版在线| 久久久久久午夜| 亚洲国产精品女人久久久| 老鸭窝亚洲一区二区三区| 久久免费黄色| 日韩亚洲成人av在线| 日韩视频免费观看高清完整版| 欧美日韩在线亚洲一区蜜芽| 午夜电影亚洲| 久久精品人人做人人爽| 亚洲国产欧美日韩精品| 亚洲黄网站在线观看| 欧美日韩午夜在线| 欧美制服丝袜| 美女啪啪无遮挡免费久久网站| av不卡免费看| 香港久久久电影| 亚洲第一二三四五区| 日韩视频在线观看| 国产欧美日韩综合一区在线观看| 久久嫩草精品久久久精品一| 欧美大片免费久久精品三p| 亚洲一区在线视频| 久久久久久婷| 亚洲一区日本| 久久影院午夜片一区| 在线亚洲一区二区| 欧美一区二区性| 亚洲久久成人| 性色av一区二区三区在线观看| 在线免费观看欧美| 一区二区三区av| 亚洲电影自拍| 亚洲与欧洲av电影| 亚洲美女在线国产| 久久国产日韩| 亚洲精品视频啊美女在线直播| 亚洲在线中文字幕| 亚洲精品国久久99热| 欧美资源在线| 亚洲欧美日韩中文视频| 欧美va天堂| 久久人人爽人人| 欧美午夜片在线免费观看| 欧美成人免费在线视频| 国产麻豆精品久久一二三| 亚洲国产成人不卡| 欧美日韩国产成人| 久久永久免费| 亚洲欧美另类久久久精品2019| 欧美在线91| 亚洲一区二区在线免费观看| 久久综合网hezyo| 久久成人一区| 欧美午夜视频网站| 亚洲人成啪啪网站| 在线精品视频一区二区| 欧美一区二区三区在线| 午夜精品免费视频| 欧美手机在线| 日韩一级精品视频在线观看| 亚洲乱码国产乱码精品精可以看| 久久精品国产精品亚洲| 久久精品一级爱片| 国产网站欧美日韩免费精品在线观看 | 久久夜色精品国产| 久久久亚洲综合| 国产美女精品视频| 一区二区三区高清| 亚洲一区二区成人在线观看| 欧美福利专区| 亚洲国产精品成人精品| 亚洲精品久久久久久久久久久| 蜜桃av一区二区| 亚洲国产一区二区三区高清 | 久久亚洲国产精品日日av夜夜| 国产精品社区| 午夜日韩视频| 老司机成人网| 亚洲国产91精品在线观看| 麻豆成人av| 亚洲人成网站在线播| 亚洲午夜黄色| 国产精品丝袜白浆摸在线| 亚洲欧美日韩一区| 久久香蕉国产线看观看网| 在线不卡亚洲| 欧美伦理影院| 亚洲天堂免费观看| 久久久不卡网国产精品一区| 激情自拍一区| 欧美久久99| 亚洲欧美成aⅴ人在线观看| 久久久久久久久久码影片| 在线电影国产精品| 欧美日本不卡视频| 亚洲欧美日韩精品久久奇米色影视| 久久久97精品| 亚洲精品中文字| 国产精品视频自拍| 久久字幕精品一区| 在线视频精品一区| 美女91精品| 亚洲一区二区三区在线看| 亚洲日本欧美日韩高观看| 欧美三级第一页| 香蕉av777xxx色综合一区| 欧美激情一区二区三区不卡| 亚洲欧美中文日韩v在线观看| 好看不卡的中文字幕| 欧美日韩国产成人精品| 久久xxxx| 日韩性生活视频| 老司机午夜精品视频在线观看| 宅男噜噜噜66一区二区66| 韩日欧美一区二区| 国产精品xnxxcom| 美脚丝袜一区二区三区在线观看| 一区二区三区国产精华| 欧美成人精品影院| 久久成人免费| 一区二区三区视频观看| 亚洲第一中文字幕在线观看| 国产精品夜色7777狼人| 欧美另类视频| 免费成人高清视频| 欧美在线视频免费| 亚洲午夜一级| 99精品99| 亚洲国产裸拍裸体视频在线观看乱了| 欧美伊人精品成人久久综合97| 夜夜爽www精品| 亚洲精品一区二区三区不| 精品动漫3d一区二区三区免费版 | 亚洲电影在线观看| 韩国v欧美v日本v亚洲v|