scope_ptr

#include <iostream>
#include <cassert>
using namespace std;

template <typename T>
class scoped_ptr
{
public:
    typedef T elememnt_type;
    explicit scoped_ptr(T* p = 0) :px(p){ cout << "scoped_ptr construct" << endl; };
    ~scoped_ptr(){ cout << "scoped_ptr deconstruct" << endl; delete px; }
    T& operator*()const
    {
        assert(px != 0);
        return *px;
    }
    T* operator->()const
    {
        assert(px != 0);
        return px;
    }
    T* get()const
    {
        return px;
    }
    void swap(scoped_ptr& p)
    {
        T* temp = p.px;
        p.px = px;
        px = temp;
    }
    void reset(T* p = 0){
        assert(p == 0 || p != px);
        scoped_ptr<T>(p).swap(*this);//这句话很吊
        //用临时对象交换指针,把p给了this对象,临时对象消亡delete this;
    }
    operator bool()
    {
        cout << "scoped_ptr operator bool()" << endl;
        return px != 0;
    }
    bool operator!()
    {
        cout << "scoped_ptr bool operator!()" << endl;
        return px == 0;
    }
private:
    T* px;
    scoped_ptr(const scoped_ptr& ptr);
    scoped_ptr& operator=(const scoped_ptr& ptr);
    bool operator==(const scoped_ptr& ptr);
    bool operator!=(const scoped_ptr& ptr);
};

int main(){
    scoped_ptr<int> p(new int(10));//scoped_ptr construct
    if (p)
    {
        cout << "p true" << endl;//p true
    }
    else
    {
        cout << "p false"<<endl;
    }
    scoped_ptr<int> p2(new int(20));
    p2.swap(p);
    cout << *p << ends << *p2 << endl;//20 10
    p2.reset(new int(100));//scoped_ptr construct scoped_ptr deconstruct 
    cout << *p << ends << *p2 << endl;//20 100
    return 0;
}

这里写图片描述

### C++ 中 `shared_ptr` 的使用方法与示例 #### 什么是 `shared_ptr` `shared_ptr` 是 C++ 标准库中的智能指针之一,用于管理动态分配的对象。它通过引用计数机制自动释放所管理对象的内存,从而避免手动调用 `delete` 导致的内存泄漏问题[^1]。 #### 创建 `shared_ptr` 可以通过多种方式创建 `shared_ptr` 对象: 1. **直接初始化** 可以通过 `new` 关键字显式创建一个对象并将其传递给 `shared_ptr` 构造函数。 ```cpp std::shared_ptr<int> ptr(new int(42)); ``` 2. **使用 `make_shared` 函数** 推荐的方式是使用 `std::make_shared` 来创建 `shared_ptr`,因为它更高效且安全性更高。 ```cpp std::shared_ptr<int> ptr = std::make_shared<int>(42); ``` #### 复制和赋值 当复制或赋值一个 `shared_ptr` 时,会增加其内部引用计数器的值。一旦最后一个 `shared_ptr` 被销毁或者重置,其所管理的对象会被自动删除。 ```cpp std::shared_ptr<Test> p0 = std::make_shared<Test>(); { std::shared_ptr<Test> p1 = p0; // 引用计数加1 { std::shared_ptr<Test> p2 = p0; // 引用计数再加1 std::cout << "Current ref count: " << p0.use_count() << std::endl; } std::cout << "After inner scope, ref count: " << p0.use_count() << std::endl; } // 当p1超出作用域后,ref count减至1;最后p0也超出作用域,则析构Test实例 ``` #### 获取引用计数 可以使用成员函数 `.use_count()` 查看当前共享此对象的 `shared_ptr` 数量。 ```cpp std::cout << "Reference count: " << ptr.use_count() << std::endl; ``` #### 自定义删除器 如果需要自定义资源清理逻辑,可以在创建 `shared_ptr` 时提供一个可调用的删除器。 ```cpp auto deleter = [](int* p) { delete[] p; }; std::shared_ptr<int[]> arrayPtr(new int[10], deleter); ``` #### 配合 `weak_ptr` 使用 为了打破循环引用导致无法释放内存的情况,通常配合 `weak_ptr` 使用。`weak_ptr` 不影响引用计数,仅观察目标是否仍然有效。 ```cpp class A : public std::enable_shared_from_this<A> {}; void func(std::weak_ptr<A> wp) { if (auto sp = wp.lock()) { // 尝试锁定弱指针wp得到强指针sp // 如果成功则继续操作... } else { // 已经被销毁 } } ``` --- ### 完整示例代码 下面是一个完整的例子展示如何使用 `shared_ptr` 和它的基本功能: ```cpp #include <iostream> #include <memory> class Resource { public: Resource(const char* name): m_name(name) { std::cout << "Resource created: " << m_name << '\n'; } ~Resource() { std::cout << "Resource destroyed: " << m_name << '\n'; } private: const char* m_name; }; int main(){ auto res = std::make_shared<Resource>("Example"); { std::shared_ptr<Resource> copy(res); // 增加引用计数 std::cout << "Use Count after copying: " << res.use_count() << "\n"; // 进一步测试其他特性... } std::cout << "Use Count before leaving main(): " << res.use_count() << "\n"; return 0; } ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值