1 public class UniquePtr<T>
2 {
3 private typedef UniquePtr<T> Self;
4
5 public nothrow UniquePtr() : ptr(null)
6 {
7 }
8 public explicit nothrow UniquePtr(T* ptr_) : ptr(ptr_)
9 {
10 }
11 suppress UniquePtr(const Self&);
12 public nothrow UniquePtr(Self&& that) : ptr(that.Release())
13 {
14 }
15 public nothrow void operator=(T* ptr_)
16 {
17 if (ptr != null)
18 {
19 delete ptr;
20 }
21 ptr = ptr_;
22 }
23 suppress void operator=(const Self&);
24 public nothrow void operator=(Self&& that)
25 {
26 if (ptr != null)
27 {
28 delete ptr;
29 }
30 ptr = that.Release();
31 }
32 public ~UniquePtr()
33 {
34 if (ptr != null)
35 {
36 delete ptr;
37 }
38 }
39 public nothrow void Reset()
40 {
41 if (ptr != null)
42 {
43 delete ptr;
44 ptr = null;
45 }
46 }
47 public nothrow void Reset(T* ptr_)
48 {
49 if (ptr != null)
50 {
51 delete ptr;
52 }
53 ptr = ptr_;
54 }
55 public inline nothrow T* Release()
56 {
57 T* ptr_ = ptr;
58 ptr = null;
59 return ptr_;
60 }
61 public inline nothrow T* Get()
62 {
63 return ptr;
64 }
65 public inline nothrow bool IsNull() const
66 {
67 return ptr == null;
68 }
69 public inline nothrow T* operator->()
70 {
71 #assert(ptr != null);
72 return ptr;
73 }
74 public inline nothrow const T* operator->() const
75 {
76 #assert(ptr != null);
77 return ptr;
78 }
79 public inline nothrow T& operator*()
80 {
81 #assert(ptr != null);
82 return *ptr;
83 }
84 public inline nothrow const T& operator*() const
85 {
86 #assert(ptr != null);
87 return *ptr;
88 }
89 public nothrow void Swap(Self& that)
90 {
91 Swap(ptr, that.ptr);
92 }
93 private T* ptr;
94 }
95
96 public class TestClass
97 {
98 public void foo()
99 {
100 System.Console.WriteLine("foo");
101 }
102 }
103
104 public void main()
105 {
106 UniquePtr<TestClass> p = new TestClass();
107 p->foo();
108 }