llvm.org GIT mirror llvm / 7143072
add new smart pointer for clang. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@45261 91177308-0d34-0410-b5e6-96231b3b80d8 Chris Lattner 12 years ago
1 changed file(s) with 79 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 //===- llvm/ADT/OwningPtr.h - Smart ptr that owns the pointee ---*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file was developed by Chris Lattner and is distributed under the
5 // University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines and implements the OwningPtr class.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_ADT_OWNING_PTR_H
14 #define LLVM_ADT_OWNING_PTR_H
15
16 #include
17
18 namespace llvm {
19
20 /// OwningPtr smart pointer - OwningPtr mimics a built-in pointer except that it
21 /// guarantees deletion of the object pointed to, either on destruction of the
22 /// OwningPtr or via an explicit reset(). Once created, ownership of the
23 /// pointee object can be taken away from OwningPtr by using the take method.
24 template
25 class OwningPtr {
26 OwningPtr(OwningPtr const &); // DO NOT IMPLEMENT
27 OwningPtr &operator=(OwningPtr const &); // DO NOT IMPLEMENT
28 T *Ptr;
29 public:
30 explicit OwningPtr(T *P = 0) : Ptr(P) {}
31
32 ~OwningPtr() {
33 delete Ptr;
34 }
35
36 /// reset - Change the current pointee to the specified pointer. Note that
37 /// calling this with any pointer (including a null pointer) deletes the
38 /// current pointer.
39 void reset(T *P = 0) {
40 if (P == Ptr) return;
41 T *Tmp = Ptr;
42 Ptr = P;
43 delete Tmp;
44 }
45
46 /// take - Reset the owning pointer to null and return its pointer. This does
47 /// not delete the pointer before returning it.
48 T *take() {
49 T *Tmp = Ptr;
50 Ptr = 0;
51 return Tmp;
52 }
53
54 T &operator*() const {
55 assert(Ptr && "Cannot dereference null pointer");
56 return *Ptr;
57 }
58
59 T *operator->() const { return Ptr; }
60 T *get() const { return Ptr; }
61 operator bool() const { return Ptr != 0; }
62 bool operator!() const { return Ptr == 0; }
63
64 void swap(OwningPtr &RHS) {
65 T *Tmp = RHS.Ptr;
66 RHS.Ptr = Ptr;
67 Ptr = Tmp;
68 }
69 };
70
71 template
72 inline void swap(OwningPtr &a, OwningPtr &b) {
73 a.swap(b);
74 }
75
76 } // end namespace llvm
77
78 #endif