C++ Primer(第5版) 练习 16.28
练习 16.28 编写你自己版本的shared_ptr和unique_ptr。
环境:Linux Ubuntu(云服务器)
工具:vim
代码块
cpp
//Shared_ptr
template <typename T> class SharedPtr {
public:
explicit SharedPtr(T* ptr = nullptr)
: ptr_(ptr), ref_count_(new int(1)) {}
SharedPtr(const SharedPtr& other)
: ptr_(other.ptr_), ref_count_(other.ref_count_) {
(*ref_count_)++;
}
SharedPtr& operator=(const SharedPtr& other) {
if (this != &other) {
release();
ptr_ = other.ptr_;
ref_count_ = other.ref_count_;
(*ref_count_)++;
}
return *this;
}
~SharedPtr() {
release();
}
T& operator*() const {
return *ptr_;
}
T* operator->() const {
return ptr_;
}
T* get() const {
return ptr_;
}
int use_count() const {
return *ref_count_;
}
private:
T* ptr_;
int* ref_count_;
void release() {
if (--(*ref_count_) == 0) {
delete ptr_;
delete ref_count_;
}
}
};
//unique_ptr
template <typename T>class UniquePtr {
public:
explicit UniquePtr(T* ptr = nullptr) : ptr_(ptr) {}
~UniquePtr() {
delete ptr_;
}
UniquePtr(const UniquePtr&) = delete;
UniquePtr& operator=(const UniquePtr&) = delete;
UniquePtr(UniquePtr&& other) noexcept : ptr_(other.ptr_) {
other.ptr_ = nullptr;
}
UniquePtr& operator=(UniquePtr&& other) noexcept {
if (this != &other) {
delete ptr_;
ptr_ = other.ptr_;
other.ptr_ = nullptr;
}
return *this;
}
T& operator*() const {
return *ptr_;
}
T* operator->() const {
return ptr_;
}
T* get() const {
return ptr_;
}
T* release() {
T* temp = ptr_;
ptr_ = nullptr;
return temp;
}
void reset(T* ptr = nullptr) {
delete ptr_;
ptr_ = ptr;
}
private:
T* ptr_;
};