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;
auto pointer3 = pointer;
int *p = pointer.get();
std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl;
std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl;
std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl;
pointer2.reset();
std::cout << "reset pointer2:" << std::endl;
std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl;
std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl;
std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl;
pointer3.reset();
std::cout << "reset pointer3:" << std::endl;
std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl;
std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl;
std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl;
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>());
if (p1) p1->foo();
{
std::unique_ptr<Foo> p2(std::move(p1));
f(*p2);
if(p2) p2->foo();
if(p1) p1->foo();
p1 = std::move(p2);
if(p2) p2->foo();
std::cout << "p2 被销毁" << std::endl;
}
if (p1) p1->foo();
}
std::weak_ptr