今天開始須要分析clang的源碼了,LLVM這個開源的project代碼寫的很不錯的,也算是鞏固一下C++的一些基礎知識了。html
首先是在llvm/ADT/OwningPtr.h中定義了owningptr智能指針的實現:函數
源碼以下:ui
1 /// OwningPtr smart pointer - OwningPtr mimics a built-in pointer except that it 2 /// guarantees deletion of the object pointed to, either on destruction of the 3 /// OwningPtr or via an explicit reset(). Once created, ownership of the 4 /// pointee object can be taken away from OwningPtr by using the take method. 5 template<class T> 6 class OwningPtr { 7 OwningPtr(OwningPtr const &) LLVM_DELETED_FUNCTION; 8 OwningPtr &operator=(OwningPtr const &) LLVM_DELETED_FUNCTION; 9 T *Ptr; 10 public: 11 explicit OwningPtr(T *P = 0) : Ptr(P) {} 12 13 #if LLVM_HAS_RVALUE_REFERENCES 14 OwningPtr(OwningPtr &&Other) : Ptr(Other.take()) {} 15 16 OwningPtr &operator=(OwningPtr &&Other) { 17 reset(Other.take()); 18 return *this; 19 } 20 #endif 21 22 ~OwningPtr() { 23 delete Ptr; 24 } 25 26 /// reset - Change the current pointee to the specified pointer. Note that 27 /// calling this with any pointer (including a null pointer) deletes the 28 /// current pointer. 29 void reset(T *P = 0) { 30 if (P == Ptr) return; 31 T *Tmp = Ptr; 32 Ptr = P; 33 delete Tmp; 34 } 35 36 /// take - Reset the owning pointer to null and return its pointer. This does 37 /// not delete the pointer before returning it. 38 T *take() { 39 T *Tmp = Ptr; 40 Ptr = 0; 41 return Tmp; 42 } 43 44 T &operator*() const { 45 assert(Ptr && "Cannot dereference null pointer"); 46 return *Ptr; 47 } 48 49 T *operator->() const { return Ptr; } 50 T *get() const { return Ptr; } 51 LLVM_EXPLICIT operator bool() const { return Ptr != 0; } 52 bool operator!() const { return Ptr == 0; } 53 bool isValid() const { return Ptr != 0; } 54 55 void swap(OwningPtr &RHS) { 56 T *Tmp = RHS.Ptr; 57 RHS.Ptr = Ptr; 58 Ptr = Tmp; 59 } 60 };
涉及知識點:this
(一)智能指針:在堆棧上實現對原始指針的控制,對RAII相當重要;相似於垃圾回收機制,智能的回收不須要的使用的指針。spa
參考:http://msdn.microsoft.com/zh-cn/vstudio/hh279674(v=vs.80).aspx.net
源碼中實現了get、reset等重要的接口函數。指針
(二)運算符重載:code
一、上述源碼的第8行當中,重載賦值運算符爲什麼返回引用呢?由於這樣返回的值既能夠當左值也能夠當右值htm
二、http://blog.csdn.net/zgl_dm/article/details/1767201blog
(三)不要返回局部變量的引用
在上述源碼能夠看到,幾個重載函數都返回了引用,可是不是局部變量的。
http://blog.sina.com.cn/s/blog_40965d3a0101eaiq.html
一旦局部變量超過做用域釋放了資源,使用的時候就會出現問題了。
(四)模板以及explicit等知識就暫且不介紹了