zoukankan      html  css  js  c++  java
  • 智能指针share_ptr记录

    shared_ptr 是一个共享所有权的智能指针,允许多个指针指向同一个对象。shared_ptr 对象除了包括一个对象的指针,还包括一个引用计数器。当每给对象分配一个share_ptr的时候,引用计数加一;每reset一个share_ptr, 或者修改对象的指向(指向其他对象或者赋值nullptr),或者局部share_ptr离开作用域,引用计数减一,当引用计数为0的时候,自动释放自己所管理的对象。

    构造:

          struct C {int* data;};
        std::shared_ptr<int> p1;
        std::shared_ptr<int> p2 (nullptr);
        std::shared_ptr<int> p3 (new int);
        std::shared_ptr<int> p4 (new int, std::default_delete<int>());
        std::shared_ptr<int> p5 (new int, [](int* p){delete p;}, std::allocator<int>());
        std::shared_ptr<int> p6 (p5);
        std::shared_ptr<int> p7 (std::move(p6));
        std::shared_ptr<int> p8 (std::unique_ptr<int>(new int));
        std::shared_ptr<C> obj (new C);
        std::shared_ptr<int> p9 (obj, obj->data);

    输出引用计数:

    拷贝和转移:

    std::shared_ptr<int> foo;
    std::shared_ptr<int> bar(new int(10));
    foo = bar; // copy
    bar = std::make_shared<int>(20); // move
    std::unique_ptr<int> unique(new int(30));
    foo = std::move(unique); // move from unique_ptr
    std::cout << "*foo: " << *foo << '
    ';
    std::cout << "*bar: " << *bar << '
    ';

    输出:

    交换控制权:

    std::shared_ptr<int> foo(new int(10));
    std::shared_ptr<int> bar(new int(20));
    foo.swap(bar);
    std::cout << "*foo: " << *foo << '
    ';
    std::cout << "*bar: " << *bar << '
    ';

    输出:

    重置:

    std::shared_ptr<int> sp;
    sp.reset(new int);
    *sp = 10;
    std::cout << *sp << '
    ';
    sp.reset(new int);
    *sp = 20;
    std::cout << *sp << '
    ';
    sp.reset();

    输出:

    判断是否是唯一的share_ptr

    std::shared_ptr<int> foo;
    std::shared_ptr<int> bar(new int);
    std::cout << "1: " << foo.unique() << '
    '; // false (empty)
    foo = bar;
    std::cout << "2: " << foo.unique() << '
    '; // false (shared with bar)
    bar = nullptr;
    std::cout << "3: " << foo.unique() << '
    '; // true

    输出:

  • 相关阅读:
    SoapUI 使用笔记
    git 使用笔记(二)
    git 使用笔记(一)
    jquery 拓展
    hdu 1024 Max Sum Plus Plus (DP)
    hdu 2602 Bone Collector (01背包)
    hdu 1688 Sightseeing (最短路径)
    hdu 3191 How Many Paths Are There (次短路径数)
    hdu 2722 Here We Go(relians) Again (最短路径)
    hdu 1596 find the safest road (最短路径)
  • 原文地址:https://www.cnblogs.com/tyche116/p/12082533.html
Copyright © 2011-2022 走看看