C++11 智能指针std::shared_ptr/std::unique_ptr/std::weak_ptr

来源:互联网 发布:数学建模中的十大算法 编辑:程序博客网 时间:2024/05/22 02:28

std::shared_ptr


std::shared_ptr 是一种智能指针,它能够记录多少个 shared_ptr 共同指向一个对象,从而消除显示的调用 delete,当引用计数变为零的时候就会将对象自动删除。
std::shared_ptr 可以通过 get() 方法来获取原始指针,通过 reset() 来减少一个引用计数,并通过get_count()来查看一个对象的引用计数。

auto pointer = std::make_shared<int>(10);auto pointer2 = pointer;    // 引用计数+1auto pointer3 = pointer;    // 引用计数+1int *p = pointer.get();             // 这样不会增加引用计数std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl;      // 3std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl;    // 3std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl;    // 3pointer2.reset();std::cout << "reset pointer2:" << std::endl;std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl;      // 2std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl;    // 0, pointer2 已 resetstd::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl;    // 2pointer3.reset();std::cout << "reset pointer3:" << std::endl;std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl;      // 1std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl;    // 0std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl;    // 0, pointer3 已 reset

std::unique_ptr


std::unique_ptr 是一种独占的智能指针,它禁止其他智能指针与其共享同一个对象,从而保证了代码的安全

#include <iostream>#include <memory>struct Foo {    Foo()      { std::cout << "Foo::Foo" << std::endl;  }    ~Foo()     { std::cout << "Foo::~Foo" << std::endl; }    void foo() { std::cout << "Foo::foo" << std::endl;  }};void f(const Foo &) {    std::cout << "f(const Foo&)" << std::endl;}int main() {    std::unique_ptr<Foo> p1(std::make_unique<Foo>());    // p1 不空, 输出    if (p1) p1->foo();    {        std::unique_ptr<Foo> p2(std::move(p1));        // p2 不空, 输出        f(*p2);        // p2 不空, 输出        if(p2) p2->foo();        // p1 为空, 无输出        if(p1) p1->foo();        p1 = std::move(p2);        // p2 为空, 无输出        if(p2) p2->foo();        std::cout << "p2 被销毁" << std::endl;    }    // p1 不空, 输出    if (p1) p1->foo();    // Foo 的实例会在离开作用域时被销毁}

std::weak_ptr

原创粉丝点击