- std::shared_ptr
std::shared_ptr 是一种智能指针,它能够记录多少个 shared_ptr 共同指向一个对象,从而消除显式的调用 delete,当引用计数变为零的时候就会将对象自动删除。
但还不够,因为使用 std::shared_ptr 仍然需要使用 new 来调用,这使得代码出现了某种程度上的不对称。
std::make_shared 就能够用来消除显式的使用 new,所以std::make_shared 会分配创建传入参数中的对象, 并返回这个对象类型的std::shared_ptr指针。例如:
std::shared_ptr 可以通过 get() 方法来获取原始指针,通过 reset() 来减少一个引用计数, 并通过use_count()来查看一个对象的引用计数。例如:
#include#include void foo(std::shared_ptr i) { (*i)++; } int main() { auto pointer = std::make_shared (10); foo(pointer); std::cout << *pointer << std::endl; auto pointer2 = pointer; auto pointer3 = pointer; int *p = pointer.get(); std::cout << "pointer.use_cout() = " << pointer.use_count() << std::endl; std::cout << "pointer2.use_cout() = " << pointer2.use_count() << std::endl; std::cout << "pointer3.use_cout() = " << pointer3.use_count() << std::endl; pointer2.reset(); std::cout << "pointer.use_cout() = " << pointer.use_count() << std::endl; std::cout << "pointer2.use_cout() = " << pointer2.use_count() << std::endl; std::cout << "pointer3.use_cout() = " << pointer3.use_count() << std::endl; pointer3.reset(); std::cout << "pointer.use_cout() = " << pointer.use_count() << std::endl; std::cout << "pointer2.use_cout() = " << pointer2.use_count() << std::endl; std::cout << "pointer3.use_cout() = " << pointer3.use_count() << std::endl; return 0; }
- unique_ptr
std::unique_ptr 是一种独占的智能指针,它禁止其他智能指针与其共享同一个对象,从而保证代码的安全:
std::unique_ptrpointer = std::make_unique (10); // make_unique 从 C++14 引入 std::unique_ptr pointer2 = pointer; // 非法
既然是独占,换句话说就是不可复制。但是,我们可以利用 std::move 将其转移给其他的 unique_ptr,例如:
#include#include 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 Foot&)" << std::endl; } int main() { std::unique_ptr p1(std::make_unique ()); if (p1) { p1->foo(); } std::unique_ptr p2(std::move(p1)); if (p2) { p2->foo(); } if (p1) { p1->foo(); } p1 = std::move(p2); if (p2) { p2->foo(); } if (p1) { p1->foo(); } }
3.week_ptr
std::weak_ptr 没有 * 运算符和 -> 运算符,所以不能够对资源进行操作,它的唯一作用就是用于检查 std::shared_ptr 是否存在,其 expired() 方法能在资源未被释放时,会返回 false,否则返回 true。



