[Lang] 智能指针

[Lang] 智能指针

智能指针能够有效简化内存管理,避免内存泄漏和悬挂指针等问题。

1. std::unique_ptr

  • 独占所有权:一个 std::unique_ptr 对象拥有其管理的对象的唯一所有权。
  • 不允许复制:不能进行复制操作,尝试复制会导致编译错误。
  • 允许移动:可以将 std::unique_ptr 对象移动到另一个 std::unique_ptr,这会转移所有权。
  • 自动释放内存:当 std::unique_ptr 超出作用域时,它会自动释放所管理的对象。
#include <memory>
#include <iostream>
using namespace std;

int main() {
    unique_ptr<int> ptr1 = make_unique<int>(10); // 使用make_unique初始化智能指针

    unique_ptr<int> ptr2 = move(ptr1); // 使用move转移所有权
    if (!ptr1) {
        cout << "ptr1 is null" << endl; 
    }
    cout << *ptr2 << endl; 

    // 自动释放ptr2指向的对象
    return 0;
}
[Running] cd "d:\CppDev\Lang\smart_pointer\" && g++ test1.cpp -o test1 && "d:\CppDev\Lang\smart_pointer\"test1
ptr1 is null
10

[Done] exited with code=0 in 0.902 seconds

2. std::shared_ptr

  • 共享所有权:多个 std::shared_ptr 可以共同拥有一个对象。
  • 引用计数:内部维护一个引用计数,跟踪多少 std::shared_ptr 对象指向同一个对象。
  • 自动释放:当最后一个指向对象的 std::shared_ptr 被销毁时,所管理的对象才会被释放。
#include <memory>
#include <iostream>
using namespace std;

int main() {
    shared_ptr<int> ptr1 = make_shared<int>(20); //使用make_shared初始化智能指针 

    shared_ptr<int> ptr2 = ptr1; // 共享所有权
    cout << *ptr2 << endl; 
    cout << "Use count: " << ptr2.use_count() << endl; // 使用use_count()查看引用计数

    ptr1.reset(); // 释放ptr1
    cout << *ptr2 << endl; 
    cout << "Use count: " << ptr2.use_count() << endl;

    // 自动释放ptr2指向的对象
    return 0;
}
[Running] cd "d:\CppDev\Lang\smart_pointer\" && g++ test2.cpp -o test2 && "d:\CppDev\Lang\smart_pointer\"test2
20
Use count: 2
20
Use count: 1

[Done] exited with code=0 in 0.977 seconds
posted @ 2024-08-13 22:56  yaoguyuan  阅读(23)  评论(0)    收藏  举报