智能指针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

输出:

原文地址:https://www.cnblogs.com/tyche116/p/12082533.html