智能指针之shared_ptr

本文探讨了C++中的auto_ptr智能指针逐渐被shared_ptr取代的原因,并通过实例展示了auto_ptr存在的问题,如不能保留指针所有权及不支持对象数组等问题。同时,给出了shared_ptr的实现代码。

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

  在智能指针中,auto_ptr已经使用的越来越少了,特别是在C++11中,它已经被shared_ptr取代,原因主要有以下两点:
  
  1. auto_ptr不能保留指针所有权

class Test
{
public:
    Test(int m) : m_test(m) {}
    ~Test();
public:
    int m_test;
};

/*********************/
void fun(auto_ptr<Test> p1)
{
    cout << p1->m_test << endl;
}

/*******************/
void main()
{
    auto_ptr<Test> p(new Test(5));
    fun(p);
    cout << p->m_test << endl;//出错
}

  上述代码中,主函数中的p作为参数传递给p1,此时p也就将所有权交给了p1,p1在fun函数执行完后释放内存块,而此时的p什么都没了,所以不再有访问内存数据的权力了。

  2.不能能指向对象数组
  这个缺点使得它不能和new[]一起使用

void main()
{
    auto_ptr<Test> p(new Test[5]);
}

  上述代码运行时会出现一个问题,当auto_ptr离开作用域时,会默认调用delete释放内存空间,对于一个对象显然是没有问题的,但是这里的p指向的是一个对象组,需要用delete[]来释放内存,而如果继续用delete就会有问题。

  基于以上两点,在实际中我们采用shared_ptr替代auto_ptr的功能。因为shared_ptr有一个引用计数功能。话不多说,下面直接给出shared_ptr的实现代码:

/****这里仅给出核心部分的代码********/
#include<iostream>
using namespace std;

template<class T>
class shared_ptr
{
private:
    T* m_ptr;
    unsigned int shared_count;
public:
    shared_ptr(T* ptr) : m_ptr(ptr), shared_ptr{}
    ~shared_ptr() {deconstruct();}

    void deconstruct()
    {
        if(shared_count == 1)
        {
            delete m_ptr;
            m_ptr = NULL;
        }
        count--;            
    }
    T* operator&() {return m_ptr;}
    T& operator*() {return *m_ptr;}

    //拷贝构造函数
    shared_ptr(shared_ptr& sp) : m_ptr(sp.m_ptr), shared_count(sp.shared_count)
    {
        shared_count++;
    }
    //赋值运算符
    shared_ptr& operator=(shared_ptr& sp)
    {
        sp.shared_count++;
        deconstruct();
        m_ptr = sp.m_ptr;
        shared_count = sp.shared_count;

        return *this;
    }
};

部分摘自:C++11智能指针

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值