简单模拟智能指针

踩坑 注意: *运算符重载如果不返回引用会导致 (*test2).show(); 段错误 为什么?
因为不加引用那么返回的是一个临时对象 是当前调用者的副本 或者说是this的副本 共享str 然后他调用show方法虽然返回了正确的输出结果但是之后立马被析构 由于 这个副本和test1 test2 他们仨共享str 所以之后这两个副本析构调用~Test析构时也出现了问题

#include <iostream>
#include <string.h>
using namespace std;
// 模拟智能指针
template <typename T>
class my_shared_ptr
{
public:
    /* 有参构造 */
    my_shared_ptr(T *obj = nullptr) : ptr(obj), count(new int(1))
    {
        cout << "有参构造" << endl;
        if (obj == nullptr)
        {
            *count = 0;
            ptr = nullptr;
        }
    }
    /* 拷贝构造 */

    my_shared_ptr(my_shared_ptr<T> &obj) : ptr(obj.ptr), count(obj.count)
    {
        cout << "拷贝构造" << endl;
        (*count)++;
    }
    /* 重载赋值符号 */
    my_shared_ptr<T> &operator=(my_shared_ptr<T> &obj)
    {
        cout << "调用重载=" << endl;
        if (this != &obj)
        {
            this->release();
            this->ptr = obj.ptr;
            this->count = obj.count;
            (*count)++;
        }
        return *this;
    }

    /* 重载 * */
    T &operator*()
    {
        return *ptr;
    }
    /* 重载 -> */ // 此处有点迷糊...比起*因为不是对自身操作 不知道返回值是什么..
    T *operator->()
    {
        return ptr;
    }
    /* 控制引用计数器 */
    void release()
    {
        (*count)--;
        if (*count == 0)
        {
            if (ptr != nullptr)
            {
                delete ptr;
                cout << "my_shared_ptr析构" << endl;
            }
            else
            {
                cout << "ptr 为空 my_shared_ptr不析构" << endl;
            }
            delete count;
        }
    }

    /* 析构 */
    ~my_shared_ptr()
    {
        release();
    }

    T *ptr;
    int *count;
};

// 模拟string类
class Test
{
public:
    Test(const char *str = nullptr)
    {
        size_t len = sizeof(str);
        this->str = new char[len];
        strcpy(this->str, str);
    }
    ~Test()
    {
        if (str != nullptr)
        {
            cout << "Test析构" << endl;

            delete[] str;
        }
        else
        {
            cout << "Test为空不用析构" << endl;
        }
    }
    void show()
    {
        cout << str << endl;
    }

private:
    char *str;
};
int main()
{
    my_shared_ptr<Test> test1(new Test("hello"));
    my_shared_ptr<Test> test2;
    cout << *(test2.count) << endl;
    test2 = test1;
    (*test2).show();
    test2->show();
    test2.operator->()->show();

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值