通过断点可以更加形象的看到程序运行过程,其中不同的注释代码可以调用。
#include<iostream>
#include<string>
#include<memory>
//通过智能指针来实现new delete 的自动化调用,本质上是一个原始指针的包装
//unique_ptr 是作用域指针,是超出作用域时,
//shared_ptr工作方式通过引用计数跟踪指针有多少个引用,引用计数达0删除
class entity
{
public:
entity()
{
std::cout << "Created entity!" << std::endl;
}
~entity()
{
std::cout << "Destroyed entity!" << std::endl;
}
void print(){}
};
int main()
{
{
std::shared_ptr<entity> e0;
//std::weak_ptr<entity>e0;
{
//std::unique_ptr<entity>e0=new entity(); unique_ptr调用了explicit 只能显式调用构造函数
//std::unique_ptr<entity>e0(new entity());
//std::unique_ptr<entity>e0 = std::make_unique<entity>();
//std::make_unique在内存分配和对象构造期间提供了异常安全保证。
// 例如,当你在函数调用中传递多个以new表达式构造的参数时,如果其中一个参数构造抛出异常,那么在这个参数之前构造的参数可能不会被删除,导致内存泄漏。
// 而std::make_unique可以防止这种情况发生。
//错误示例 std::unique_ptr<entity>e1= e0;拷贝构造函数与操作符实际被删除了
std::shared_ptr<entity>sharedentity = std::make_shared<entity>();
//std::shared_ptr<entity>sharedentity(new entity());
//std::weak_ptr<entity>weakentity = sharedentity;//不增加引用计数
e0 = sharedentity;
}
}
std::cin.get();
}
weak_ptr 与shared_ptr作用不同 在离开第一个作用域weak_ptr立即销毁而shared_ptr在第二个作用域进行销毁。unique_ptr优先使用, shared_ptr更适合对象间共享。