4种智能指针

C++11 中提供了四种智能指针类型:unique_ptr、shared_ptr、weak_ptr 和 auto_ptr(已废弃)。以下是对四种智能指针的举例说明:

1. unique_ptr

unique_ptr 是一种独占式智能指针,它拥有对对象的唯一所有权,不能被多个 unique_ptr 对象共享。当 unique_ptr 对象被销毁时,它所管理的对象也会被销毁。unique_ptr 的使用示例:```c++

#include <iostream>
#include <memory>

using namespace std;

int main() {
    unique_ptr<int> p(new int(10));
    cout << *p << endl; // 输出 10
    *p = 20;
    cout << *p << endl; // 输出 20
    return 0;
}


```

2. shared_ptr

shared_ptr 是一种共享式智能指针,可以被多个 shared_ptr 对象共享同一个对象,当最后一个 shared_ptr 对象销毁时,它所管理的对象也会被销毁。shared_ptr 使用引用计数来管理对象的生命周期。shared_ptr 的使用示例:```c++

#include <iostream>
#include <memory>

using namespace std;

int main() {
    shared_ptr<int> p1(new int(10));
    shared_ptr<int> p2(p1);
    cout << *p1 << endl; // 输出 10
    cout << *p2 << endl; // 输出 10
    *p1 = 20;
    cout << *p2 << endl; // 输出 20
    return 0;
}


```

3. weak_ptr

weak_ptr 是一种弱引用智能指针,不能单独管理对象的生命周期,它只能指向被 shared_ptr 管理的对象,用于解决 shared_ptr 循环引用的问题。weak_ptr 不会增加对象的引用计数,当最后一个 shared_ptr 对象销毁时,weak_ptr 不会影响对象的销毁。weak_ptr 的使用示例:```c++

#include <iostream>
#include <memory>

using namespace std;

int main() {
    shared_ptr<int> p1(new int(10));
    weak_ptr<int> p2(p1);
    cout << *p1 << endl; // 输出 10
    cout << *(p2.lock()) << endl; // 输出 10
    *p1 = 20;
    cout << *(p2.lock()) << endl; // 输出 20
    return 0;
}


```

4. auto_ptr

auto_ptr 是一种自动指针,可以自动管理对象的生命周期,但它已经被废弃,不再建议使用。auto_ptr 在将资源转移给另一个 auto_ptr 时,会自动释放原来的资源,可能会导致不可预期的行为。auto_ptr 的使用示例:```c++

#include <iostream>
#include <memory>

using namespace std;

int main() {
    auto_ptr<int> p1(new int(10));
    auto_ptr<int> p2(p1);
    cout << *p2 << endl; // 输出 10
    return 0;
}


```

以上是四种智能指针的使用示例,需要注意的是,智能指针并不是万能的,需要根据实际情况选择合适的智能指针类型,避免出现问题。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值