- c++中的内存的分配和释放是由程序员自己规划。智能指针不需要自己去delete一个new的对象,会自动释放对应的内存空间。
- unique_ptr:作用域指针,超出作用域后自动释放分配的内存区域。unique是指唯一,不能复制一个unique_ptr指针,因为如果复制一个unique_ptr指针,则这两个指针指向同样的内存, 当一个指针释放该区域的内存,另一个复制的指针就会指向一块被释放的内存地址。
-
#include <iostream> #include <string> #include <memory>class Entity { public:int x, y;Entity(){std::cout << "这是构造函数!!!" << std::endl;}~Entity(){std::cout << "这是析构函数!!!" << std::endl;} }; int main() {{//std::unique_ptr<Entity> e(new Entity());//异常安全,会对构造函数抛出的异常进行捕获std::unique_ptr<Entity> e = std::make_unique<Entity>();}std::cin.get();return 0; }
-
shared_ptr共享指针:shared_ptr工作方式是通过引用计数跟踪指针的引用数量,当引用计数为0时,释放内存。
-
#include <iostream> #include <string> #include <memory>class Entity { public:int x, y;Entity(){std::cout << "这是构造函数!!!" << std::endl;}~Entity(){std::cout << "这是析构函数!!!" << std::endl;} }; int main() {{std::shared_ptr<Entity> e2;{std::shared_ptr<Entity> e1 = std::make_shared<Entity>();e2 = e1;}}std::cin.get();return 0; }
-
weak_ptr:j结合share_ptr使用,weak_ptr不会增加引用计数。但share_ptr会增加应用计数。
-
#include <iostream> #include <string> #include <memory>class Entity { public:int x, y;Entity(){std::cout << "这是构造函数!!!" << std::endl;}~Entity(){std::cout << "这是析构函数!!!" << std::endl;} }; int main() {{std::weak_ptr<Entity> w;{std::shared_ptr<Entity> e1 = std::make_shared<Entity>();w = e1;}}std::cin.get();return 0; }