一篇文章带你搞定手写unique_ptr智能指针

相比于shared_ptr智能指针来说,unique_ptr智能指针较为简单,但是是面试场上常问的问题。属于应该掌握的知识点。

unique_ptr实现

#include <iostream>
using namespace std;

class Type
{
public:
    int a = 1;
};

template<typename T>
class smart_ptr
{
public:
    smart_ptr(T* ptr = NULL) : m_ptr(ptr) {}
    ~smart_ptr() {
        delete m_ptr;
    }
    T& operator*() const { return *m_ptr; }
    T* operator->() const { return m_ptr; }
    operator bool() const { return m_ptr; }

    // 搬移构造
    smart_ptr(smart_ptr&& rhs) noexcept {
        m_ptr = rhs.m_ptr;
        rhs.m_ptr = NULL;
    }
    // 搬移赋值
    smart_ptr& operator=(smart_ptr&& rhs) noexcept {
        m_ptr = rhs.m_ptr;
        rhs.m_ptr = NULL;
        return *this;
    }
private:
    T* m_ptr;
};

int main()
{
    smart_ptr<Type> sptr(new Type);
    smart_ptr<Type> sptr2(std::move(sptr));  // 调用搬移构造
    smart_ptr<Type> sptr3;
    sptr3 = std::move(sptr2);  // 调用搬移赋值
    return 0;
}
#面经#
全部评论
点赞 回复 分享
发布于 2022-08-24 08:08 江苏
这个作者请问下25行不是右值吗,这个也可以赋值为空吗
点赞 回复 分享
发布于 2022-06-23 11:59
哎,一文搞不定的,还要自己多练习才行的
点赞 回复 分享
发布于 2022-06-18 17:18

相关推荐

今天 11:12
门头沟学院 Java
真的是误闯天家了,太难了
投递虾皮信息等公司7个岗位
点赞 评论 收藏
分享
06-07 17:17
嘉兴学院 教师
心爱的idea:你孩
点赞 评论 收藏
分享
07-28 16:37
门头沟学院 Java
哎,继续加油吧
ResourceUt...:能接到面试就已经是✌🏻了
腾讯一面2194人在聊
点赞 评论 收藏
分享
评论
11
38
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务