• 【Cherno的C++视频】Smart pointers in C++


    #include 
    #include 
    
    // std::unique_ptr, std::shared_ptr, std::weak_ptr.
    // smart pointers, when you call new, you don't have to call delete. 
    // It's a wrapper around a real raw pointer, it'll call new when you make it.
    //
    // unique_ptr:scoped pointer, it will get destroyed if it goes out of scope. can't be copied.
    // 
    // shared_ptr:working by reference counting, keeps track of how many references you have to your pointer,
    // as soon as that reference count reaches 0 that's when it gets deleted. can be copied.
    //
    // weak_ptr:assign a shared_ptr to another shared_ptr, it will increase the reference count but 
    // when you assign a shared_ptr to a weak_ptr it won't increase the reference count.
    //
    // unique_ptr has a lower overhead, but shared_ptr is also useful in some cases, so is weak_ptr.
    
    class Entity
    {
    public:
    	Entity(){ std::cout << "Created Entity!" << std::endl; }
    
    	~Entity(){ std::cout << "Destroyed Entity!" << std::endl; }
    
    	void Function(){}
    };
    
    int main(void)
    {
    	{
    		std::shared_ptr<Entity> e0;
    		{
    			//std::unique_ptr entity = std::make_unique();//more preferred way, slightly safer than std::unique_ptr uniqueEntity(new Entity());
    			//entity->Function();
    			std::unique_ptr another = entity;//error, can't copy a unique pointer.
    
    			std::shared_ptr<Entity> sharedEntity = std::make_shared<Entity>();
    			//std::shared_ptr sharedEntity(new Entity());//can do this too.
    			//std::shared_ptr another = sharedEntity;//works.
    			e0 = sharedEntity;//works.
    
    			std::weak_ptr<Entity> weakEntity = sharedEntity;
    		}
    	}
    
    	std::cin.get();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
  • 相关阅读:
    04 python的函数
    关于原型的一些总结
    【华为OD机试真题 python】九宫格按键输入法【2022 Q4 | 200分】
    react中的非受控组件与受控组件
    X86_64函数调用汇编程序分(2)
    8月8日下午6:00面试总结
    Git:使用conda命令切换虚拟环境
    Java基础知识面试高频考点
    Spring中的事务与事务传播机制
    react —— useState 深入
  • 原文地址:https://blog.csdn.net/AlexiaDong/article/details/126312823