智能指针的简单实现

本文探讨了C++中智能指针的基本概念,并通过示例介绍了如何简单实现一个智能指针,以解决手动内存管理的问题。智能指针通过自动释放所指向的对象,防止内存泄漏,是C++现代内存管理的重要工具。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <assert.h>
using namespace std;


class A {
public:
    A(int a, int b) {
        x = a;
        y = b;
    };
    int x;
    int y;

    void test() {
        cout << "hello test!" << endl;
    };
};

template<typename T>
class smartPtr {
public:
    smartPtr() {
        cout << "default construct" << endl;
        _ptr = nullptr;
        _cont = nullptr;
    };

    smartPtr(T * ptr) {
        cout << "normal construct" << endl;
        _ptr = ptr;
        _cont = new int();
        (*_cont) = 1;
    };

    smartPtr(const smartPtr& sp) {
        cout << "copy construct" << endl;
        _ptr = sp._ptr;
        _cont = sp._cont;
        (*_cont)++;
    };

    smartPtr & operator=(const smartPtr& sp) {
        cout << "operator =" << endl;
        if(this->_ptr != sp._ptr) {  // 防止自赋值
            if(_ptr != nullptr) {
                (*_cont)--;
                if((*_cont) == 1) {
                    delete _ptr;
                    _ptr = nullptr;
                    delete _cont;
                    _cont = nullptr;

                }
            }
            _ptr = sp._ptr;
            _cont = sp._cont;
            (*_cont)++;
        }
        return *this;
    }

    ~smartPtr() {
        cout << "destructor" <<endl;
        if(_ptr != nullptr) {   // 指针非空时
            if((*_cont) == 1) {  // 引用计数将减为 0
                cout << "delete object" << endl;
                delete _ptr;
                _ptr = nullptr;
                delete _cont;
                _cont = nullptr;
            } else {
                (*_cont)--;  // 引用计数减小
            }
        }
    };


    T & operator*() {
        assert(_ptr != nullptr);
        return *_ptr;
    }

    T * operator->() {
        assert(_ptr != nullptr);
        return _ptr;
    }

    int getCount() {
        if(_cont != nullptr)
            return *_cont;
        return -1;
    }




private:
    T * _ptr;
    int * _cont;

};


int main()
{
    double * a = new double(10.2);
    int * b = new int(3);
    A * c = new A(1,2);
    smartPtr<double>s(a);
    smartPtr<int> s2(b);
    smartPtr<int> s3 = s2;
    smartPtr<A> s4(c);
    smartPtr<A> s5 = s4;

    s2 = s3;

    cout << *s << endl;
    cout << s.getCount() << endl;
    cout << *s2 << endl;
    cout << s.getCount() << endl;
    cout << s2.getCount() << endl;
    cout << *s3 << endl;
    cout << s.getCount() << endl;

    cout << s4->x << " " << s4->y << endl;
    s4->test();
    cout << s5->x << " " << s5->y << endl;
    cout << s5.getCount() << endl;


    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值