Templates -- Meow  1.1.2
不能,也不應該先編譯成obj-file的templates
Self.h
Go to the documentation of this file.
1 #ifndef Self_h__
2 #define Self_h__
3 
4 #include <cstdlib>
5 
6 namespace meow {
7 
68 template<class Data>
69 class Self {
70 private:
71  class Body {
72  private:
73  struct Kernel {
74  Data data_;
75  int counter_;
76  Kernel() {
77  counter_ = 1;
78  }
79  Kernel(Data const& data) {
80  counter_ = 1;
81  data_.copyFrom(data);
82  }
83  };
84  Kernel *pointer_;
85  int counter_;
86  public:
87  Body() {
88  counter_ = 1;
89  pointer_ = new Kernel;
90  }
91  Body(Body const& b) {
92  counter_ = 1;
93  pointer_ = b.pointer_;
94  pointer_->counter_++;
95  }
96  ~Body() {
97  pointer_->counter_--;
98  if (pointer_->counter_ <= 0) {
99  delete pointer_;
100  }
101  }
102  int attatch() { return ++counter_; }
103  int detatch() { return --counter_; }
104  Data const* access() const { return &(pointer_->data_); }
105  Data * modify() {
106  if (pointer_->counter_ > 1) {
107  pointer_->counter_--;
108  pointer_ = new Kernel(pointer_->data_);
109  }
110  return &(pointer_->data_);
111  }
112  };
113  Body* body_;
114 
115  void clear(Body* body) {
116  if (body != NULL) {
117  if (body->detatch() <= 0) {
118  delete body;
119  }
120  }
121  }
122 public:
130  Self(bool create_body) {
131  body_ = (create_body ? new Body() : NULL);
132  }
133 
135  Self(Self const& b);
136 
138  ~Self() {
139  clear(body_);
140  }
141 
143  Data const* operator->() const {
144  return body_->access();
145  }
146 
148  Data* operator->() {
149  return body_->modify();
150  }
151 
153  Self& operator()() const {
154  return *((Self*)this);
155  }
156 
166  void copyFrom(Self const& s) {
167  Body* old = body_;
168  body_ = new Body(*(s.body_));
169  clear(old);
170  }
171 
183  void referenceFrom(Self const& s) {
184  if (body_ != s.body_) {
185  clear(body_);
186  body_ = s.body_;
187  body_->attatch();
188  }
189  }
190 
197  bool same(Self const& s) const {
198  return (body_ == s.body_);
199  }
200 
209  bool equal(Self const& s) const {
210  if (same(s) || body_->access() == s.body_->access()) return true;
211  return (body_->access()->equal(*(s.body_->access())));
212  }
213 
220  bool referenceLess(Self const& s) const {
221  return (body_ < s.body_);
222  }
223 
225  void operator=(Self const& a);
226 };
227 
228 } // meow
229 
230 #endif // Self_h__