auto_ptr的简单实现

本文探讨了C++中的auto_ptr,包括其如何通过重载操作符&、*和->实现类似指针的行为。同时强调了使用auto_ptr时的几个重要禁忌:不应将其作为STL容器的元素、避免用作数组、不应作为容器成员,并且不推荐使用赋值操作来初始化。最后指出auto_ptr构造函数的explicit特性。

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

#include <iostream>
#include <stack>
#include <stdio.h>

using namespace std;

template <class T>
class AutoPtr{
private:
    T *m_ptr;
public:
    explicit AutoPtr(T *p=0): m_ptr(p){}
    AutoPtr (AutoPtr &a):m_ptr(a.release()){}//拷贝构造函数,将原值拷贝,并设为0

    AutoPtr &operator = (AutoPtr &a) {
        if(this == &a)
            return *this;
        delete m_ptr;
        m_ptr = a.release();

        return *this;
    }

    ~AutoPtr() {
        delete m_ptr;
    }
    
    T& operator *(){
        return *m_ptr;
    }

    T* operator ->() {
        return m_ptr;
    }

    T *get() {
        return m_ptr;
    }

    T* release() {//返回指针,并自己设为0
        T *tmp = m_ptr;
        m_ptr = 0;
        return tmp;
    }

    void reset(T *p = 0) {
        if (p != m_ptr) {
            delete m_ptr;
            m_ptr = p;
        }
    }


};

int main() {
    AutoPtr<int > t(new int(1));
}

1.    auto_ptr重载了操作符&,*和->。不要被语法误导,记住pstr是一个对象,不是一个指针。只是它重载了这些操作符后, 使用上相指针一样.

2.    不要将auto_ptr对象作为STL容器的元素。C++标准明确禁止这样做,否则可能会碰到不可预见的结果

3.    不要将数组作为auto_ptr的参数, 可以理解到在auto_ptr中, 使用delete, 但没有使用delete [].

4. auto_ptr不能作为容器的成员。

5. 不能通过赋值操作来初始化auto_ptr

std::auto_ptr<int> p(new int(42));     // OK

std::auto_ptr<int> p = new int(42);    // ERROR

这是因为auto_ptr 的构造函数被定义为了explicit





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值