C++ 11 标准中改用unique_ptr、shared_ptr、weak_ptr等智能指针来自动回收堆分配的对象。
unique_ptr与所指对象的内存绑定紧密,不能与其他unique_ptr类型的指针对象共享所指对象的内存。unique_ptr则是一个删除了拷贝构造函数、保留了移动构造函数的指针分装类型。
shared_ptr允许多个该智能指针共享同一堆分配对象的内存。
weak_ptr可以指向shared_ptr指针指向的对象内存,却并不拥有该内存。
普通智能指针:
template <typename T>
class SmartPtr{
private:
T * ptr_;
public:
SmartPtr(): ptr_(nullptr){}
explicit SmartPtr(T *t): ptr_(t){}
~ SmartPtr(){
delete ptr_;
}
T & operator*(){
return *ptr_;
}
T* operator->(){
return ptr_;
}
}
share_ptr:
#include <mutex>
template <typename T>
class SharePtr {
pravite:
T *ptr_;
int * ref_;
mutable std::mutex mut_;
void release(){
std::lock_guard<std::mutex> guard(mut_);
--(*(ref_));
if (*(ref_) == 0){
delete ptr_;
delete ref_;
ptr_ = nullptr;
ref_ = nullptr;
}
}
void addref(){
std::lock_guard<std::mutex> guard(mut_);
++(*(ref_));
}
public:
T & operator*(){return *ptr_;}
T * operator->() {return ptr_;}
explicit SharePtr(T *t): ptr_(t), ref_(new int(1)){}
explicit SharePtr(const sharePtr<T> & sp) {
//release();
ptr_ = sp.ptr_;
ref_ = sp.ref_;
addref();
}
~ share_ptr(){
release();
}
SharePtr<T>* operator=(const SharePtr <T>sp){
if (this !=sp){
release();
ptr_ = sp.ptr_;
ref_ = sp.ref_;
addref();
}
return this;
}
T * get(){return ptr_;}
}
unique_ptr:
template<typename T>
class UniquePtr{
pravite:
T * ptr_;
public:
explicit UniquePtr(T * ptr=nullptr): ptr_(ptr){}
~UniquePtr(){
if (ptr_ != nullptr){
delete ptr_;
}
}
UniquePtr(UniquePtr && ptr) noexcept
{
if (ptr_ != nullptr)
{
delete ptr_;
ptr_ = nullptr;
}
ptr_ = ptr.ptr_;
ptr.ptr_ = nullptr;
}
UniqurePtr & operator=(UniquePtr && ptr) noexcept
{
if (ptr_ != nullptr)
{
delete ptr_;
ptr_ = nullptr;
}
ptr_ = ptr.ptr_;
ptr.ptr_ = nullptr;
return *this;
}
UniquePtr(const UniquePtr & ptr)=delete;
UniquePtr& operator=(const UniquePtr &ptr) = delete;
T* operator*()const noexcept {return ptr_;}
T& operator->() const noexcept {return *ptr_;}
explicit operator bool()const noexcept {return ptr_;}
T* get() const noexcept {return ptr_;}
void reset(T *ptr=nullptr) noexcept
{
if (ptr_ != nullptr)
delete ptr_;
ptr_ = ptr;
}
T * release() noexcept {
T *res = ptr_;
delete ptr_;
return res;
}
}
weak_ptr:
#include <memory>
using namespace std;
template <typename T>
class WeakPtr {
pravite:
T * ptr_;
int * ref_;
public:
WeakPtr(): ptr_(null_ptr), ref_(nullptr){}
WeakPtr(const share_ptr<T> & sp): ptr_(sp.ptr_), ref_(sp.ref_){}
WeakPtr(const WeakPtr<T> & wp): ptr_(wp.ptr_), ref_(wp.ref_){}
WeakPtr & operator=(const WeakPtr<T> wp) noexcept
{
ptr_ = wp.ptr_;
ref_ = wp.ref_;
return *this;
}
WeakPtr & operator=(const share_ptr<T> sp) noexcept
{
ptr_ = sp.ptr_;
ref_ = sp.ref_;
return *this;
}
share_ptr<T> lock() noexcept
{
return share_ptr<T> (*this);
}
bool expired() noexcept
{
if ( ref_ != nullptr){
if ((*ref_) > 0)
return ture;
}
return false;
}
int use_count() noexcept
{
if (ref_ != nullptr){
return *ref_;
}
return 0;
}
void reset() noexcept {
ptr_ = nullptr;
ref_ = nullptr;
}
}