0
点赞
收藏
分享

微信扫一扫

C/C++面试:手写智能指针类

jjt二向箔 2022-01-21 阅读 34
template<class T>
class SharedPtr{
public:
    SharedPtr()
     : m_ptr(nullptr)
     , m_count_(new size_t)
    {
    }
    
    SharedPtr(T *ptr)
    : m_ptr(ptr)
    , m_count_(new size_t)
    {
        *m_count_ = 1;
    }
    
    ~SharedPtr(){
        --(*m_count_);
        if(*m_count_ == 0){
            delete m_ptr;
            delete m_count_;
            m_ptr = nullptr;
            m_count_ = nullptr;
        }
    }
    //拷⻉构造函数
    SharedPtr(const SharedPtr& ptr){
        m_count_ = ptr.m_count_;
        m_ptr = ptr.m_ptr;
        ++(*m_count_);
    }
    //拷⻉赋值运算
    void operator=(const SharedPtr& ptr){
        SharedPtr(std::move(ptr));
    }
    //移动构造函数
    SharedPtr(SharedPtr && ptr)
    : m_ptr(ptr.m_ptr)
    , m_count_(ptr.m_count_)
    {
        ++(*m_count_);
    }
    // 移动赋值运算
    void operator=(SharedPtr && ptr){
        SharedPtr(std::move(ptr));
    }
    // 解引⽤
    T & operator*(){
        return *m_ptr;
    }
    // 箭头运算
    T* operator->(){
        return m_ptr;
    }
    // ᯿载bool操作符
    operator bool(){
        return m_ptr == nullptr;
    }
    T *get(){
        return m_ptr;
    }
    size_t use_count(){
        return *m_count_ ;
    }
    bool unique(){
        return *m_count_ == 1;
    }
    void swap(SharedPtr & ptr){
        std::swap(*this, ptr);
    }
private:
    size_t  *m_count_;
    T       *m_ptr;
};

举报

相关推荐

C++——智能指针

【C++】智能指针

C++ 智能指针

C++智能指针

C\C++_指针_智能指针模板类

C++ 11 智能指针

0 条评论