温馨提示×

C++中如何进行智能指针的使用

c++
小樊
81
2024-10-27 07:56:09
栏目: 编程语言

在 C++ 中,智能指针是一种对象,它允许对原始指针进行更安全和更方便的操作。智能指针可以自动管理指向的对象的生命周期,当智能指针不再需要时,它会自动删除所指向的对象。

C++ 中常见的智能指针有 unique_ptrshared_ptrweak_ptr

  1. unique_ptr

unique_ptr 是一种独占所有权的智能指针,它保证同一时刻只有一个 unique_ptr 可以指向一个对象。当 unique_ptr 被销毁时(例如离开其作用域),它所指向的对象也会被自动删除。

示例代码:

#include <iostream>
#include <memory>

struct Foo {
    Foo() { std::cout << "Foo::Foo\n"; }
    ~Foo() { std::cout << "Foo::~Foo\n"; }
};

void func(std::unique_ptr<Foo> ptr) {
    std::cout << "func: ptr.use_count() = " << ptr.use_count() << '\n';
}

int main() {
    std::unique_ptr<Foo> ptr(new Foo);
    std::cout << "ptr.use_count() = " << ptr.use_count() << '\n';
    func(std::move(ptr));
    std::cout << "ptr.use_count() = " << ptr.use_count() << '\n';
    return 0;
}

输出结果:

Foo::Foo
func: ptr.use_count() = 2
Foo::~Foo
func: ptr.use_count() = 1
Foo::~Foo
  1. shared_ptr

shared_ptr 是一种共享所有权的智能指针,它允许多个 shared_ptr 对象共享同一个对象。shared_ptr 使用引用计数来跟踪指向同一个对象的 shared_ptr 对象数量。当最后一个指向对象的 shared_ptr 被销毁时,对象会被自动删除。

示例代码:

#include <iostream>
#include <memory>

struct Foo {
    Foo() { std::cout << "Foo::Foo\n"; }
    ~Foo() { std::cout << "Foo::~Foo\n"; }
};

void func(std::shared_ptr<Foo> ptr) {
    std::cout << "func: ptr.use_count() = " << ptr.use_count() << '\n';
}

int main() {
    std::shared_ptr<Foo> ptr1(new Foo);
    std::cout << "ptr1.use_count() = " << ptr1.use_count() << '\n';
    {
        std::shared_ptr<Foo> ptr2 = ptr1;
        std::cout << "ptr1.use_count() = " << ptr1.use_count() << '\n';
        std::cout << "ptr2.use_count() = " << ptr2.use_count() << '\n';
    }
    std::cout << "ptr1.use_count() = " << ptr1.use_count() << '\n';
    func(ptr1);
    std::cout << "ptr1.use_count() = " << ptr1.use_count() << '\n';
    return 0;
}

输出结果:

Foo::Foo
ptr1.use_count() = 1
func: ptr1.use_count() = 2
Foo::~Foo
func: ptr1.use_count() = 1
Foo::~Foo
  1. weak_ptr

weak_ptr 是一种弱引用智能指针,它不拥有指向的对象,只是观察对象。weak_ptr 可以用来避免 shared_ptr 之间的循环引用问题。weak_ptr 可以升级为 shared_ptr,如果原 shared_ptr 仍然存在,则升级成功,否则升级为空 shared_ptr

示例代码:

#include <iostream>
#include <memory>

struct Foo {
    Foo() { std::cout << "Foo::Foo\n"; }
    ~Foo() { std::cout << "Foo::~Foo\n"; }
};

void func(std::weak_ptr<Foo> wp) {
    if (auto sp = wp.lock()) {
        std::cout << "func: sp.use_count() = " << sp.use_count() << '\n';
    } else {
        std::cout << "func: wp has expired\n";
    }
}

int main() {
    std::shared_ptr<Foo> ptr1(new Foo);
    std::weak_ptr<Foo> wp = ptr1;
    func(wp);
    std::cout << "ptr1.use_count() = " << ptr1.use_count() << '\n';
    return 0;
}

输出结果:

Foo::Foo
func: sp.use_count() = 1
Foo::~Foo
ptr1.use_count() = 1

0