智能指针

The make_shared() version mentions X only once, so it is usually shorter (as well as faster) than the version with the explicit new.

引用计数的出现,解决了对象独占的问题,但是也带来了循环引用的困扰,使用weak_ptr可以打破这种循环。

weak_ptr本身设计的很简单,就是为了辅助shared_ptr的,它本身不能直接定义指向原始指针的对象,只能指向shared_ptr对象,同时也不能将weak_ptr对象直接赋值给shared_ptr类型的变量,最重要的一点是赋值给它不会增加引用计数。

测试weak_ptr常用函数的用法

weak_ptr中只有函数lock和expired两个函数比较重要,因为它本身不会增加引用计数,所以它指向的对象可能在它用的时候已经被释放了,所以在用之前需要使用expired函数来检测是否过期,然后使用lock函数来获取其对应的shared_ptr对象,然后进行后续操作。

weak_ptr虽然是一个模板类,但是不能用来直接定义指向原始指针的对象。

weak_ptr接受shared_ptr类型的变量赋值,但是反过来是行不通的,需要使用lock函数。

weak_ptr设计之初就是为了服务于shared_ptr的,所以不增加引用计数就是它的核心功能。

由于不知道什么之后weak_ptr所指向的对象就会被析构掉,所以使用之前请先使用expired函数检测一下。

Any type (including primary template or specialization) that overloads unary * and -> is considered a smart pointer:

If it is copyable, it is recognized as a reference-counted shared_ptr.

If it is not copyable, it is recognized as a unique unique_ptr.

std::unique_ptr is the C++11 replacement for std::auto_ptr. It should be used to manage any dynamically allocated object that is not shared by multiple objects. That is, std::unique_ptr should completely own the object it manages, not share that ownership with other classes.

Remember, when a std::shared pointer goes out of scope, it only considers whether other std::shared_ptr are co-owning the object. std::weak_ptr does not count!