智能指针的简单实现
shared_ptr
namespace bobby {
class shared_count {
public:
shared_count(): count_(1){}
void add_count() {
count_++;
}
void reduce_count() {
count_--;
}
long get_count() {
return count_;
}
private:
long count_;
};
template <typename T>
class shared_ptr {
public:
shared_ptr(): ptr(nullptr){}
shared_ptr(T *p) {
if (p) {
ptr = p;
shared_count = new class shared_count();
}
}
~shared_ptr() {
release();
}
void release() {
if (!ptr) {
return;
}
shared_count->reduce_count();
if (shared_count->get_count() == 0) {
std::cout << "delete" << std::endl;
delete ptr;
delete shared_count;
}
}
shared_ptr(const shared_ptr<T> &other) {
ptr = other.ptr;
if (ptr) {
other.shared_count->add_count();
shared_count = other.shared_count;
}
}
shared_ptr(const shared_ptr<T> &&other) {
ptr = other.ptr;
if (ptr) {
shared_count = other.shared_count;
}
other.ptr = nullptr;
other.shared_count = nullptr;
}
shared_ptr &operator=(shared_ptr<T> &other) {
release();
ptr = other.ptr;
if (ptr) {
other.shared_count->add_count();
shared_count = other.shared_count;
}
return *this;
}
long get_count() {
if (ptr) {
return shared_count->get_count();
} else {
return 0;
}
}
T *get() const {return ptr;}
T &operator*() const {return *ptr;}
T *operator->() const {return ptr;}
operator bool() const {return ptr;}
private:
T* ptr;
shared_count* shared_count;
};
}
unique_ptr
namespace bobby {
template <typename T>
class unique_ptr {
public:
unique_ptr(): ptr(nullptr){}
unique_ptr(T* p){
ptr = p;
}
~unique_ptr() {
del_pointer();
}
unique_ptr(unique_ptr<T> &&other) {
ptr = other.release();
}
unique_ptr &operator=(unique_ptr<T> &&other) {
del_pointer();
ptr = other.release();
return *this;
}
T *get() {
return ptr;
}
T *get() const { return ptr; }
T &operator*() const { return *ptr; }
T *operator->() const { return ptr; }
operator bool() const { return ptr; }
T *release() {
T *p = ptr;
ptr = nullptr;
return p;
}
private:
void del_pointer() {
if (ptr) {
std::cout << "delete" << std::endl;
delete ptr;
}
}
T* ptr;
unique_ptr(unique_ptr<T> &other) = delete;
unique_ptr &operator=(unique_ptr<T> &other) = delete;
};
} // namespace bobby