1、auto_ptr的简单实现
auto_ptr的性质:会转让所有权(当拷贝构造或者复制赋值发生时)
template<class T>
class auto_ptr {
private:
T *m_ptr;
T * release() {
T *value = m_ptr;
m_ptr = 0;
return value;
}
public:
auto_ptr<T>(T *_p=0): m_ptr(_p) {}
auto_ptr<T>(const auto_ptr<T> ©) :m_ptr(copy.release()) {}
auto_ptr<T>& operator=(const auto_ptr<T> &assign) {
if (this != &assign) {
delete m_ptr;
m_ptr = assign.release();
}
return *this;
}
T& operator *() { return *m_ptr; }
T * operator ->() {return m_ptr; }
~auto_ptr<T>() { delete m_ptr; }
};
2、带有引用计数的智能指针的实现
template<typename T>
class countedPtr {
private:
T *m_ptr;
long *count;
void dispose() {
if (-- *count == 0) {
delete count;
delete m_ptr;
}
}
public:
explicit countedPtr<T>(T *_p): m_ptr(_p), count(new long(1)) {}
countedPtr<T>(const countedPtr<T> ©): m_ptr(copy.m_ptr), count(copy.count) {
++ *count;
}
countedPtr<T>& operator=(const countedPtr<T> & assign) {
if (this != &assign) {
dispose();
m_ptr = assign.m_ptr;
count = assign.count;
++ *count;
}
return *this;
}
T & operator *() { return *m_ptr; }
T * operator->() { return m_ptr; }
~countedPtr() { dispose(); }
};