Smart pointers in C++

Smart pointers in C++

What new and delete does?‘new’ allocates memory on the heap and delete is needed to delete that memory to free that memory because it won’t be freed automatically.
Smart pointers are a way to automate that process that’s all they are.
Smart pointers are essentially a wrapper around a real raw pointer.

Unique pointer

Unique pointer is a script pointer meaning that when that pointer goes out of scope it will get destroyed and it will call delete.
Unique pointer can’t not copy.
Here is the code:

#include <iostream>
#include <string>
#include <memory>

class Entity
{
public:
	Entity()
	{
		std::cout << "Created Entity!" << std::endl;
	};
	~Entity()
	{
		std::cout << "Destroyed Entity!" << std::endl;
	};
	
	void Print()
	{
	}

};

int main()
{
	{
		std::unique_ptr<Entity> entity = std::make_unique<Entity>();

		entity->Print();
	}

	std::cin.get();
}

And the unique pointer can’t be copy, the copy constructor and the copy assignment operator are actually deleted

    unique_ptr(const unique_ptr&) = delete;
    unique_ptr& operator=(const unique_ptr&) = delete;

which is why you get a compile error if you try and do something like:

std::unique_ptr<Entity> e0 = entity;

Share pointer

Share pointer is a kind of a bit differently, it’s a bit more hardcore because it does a lot of other stuff under the hood.
The way that a shared pointer implemented is using something called reference counting;
Share pointer works via reference counting is basically a practice where you keep track of how many references you have to your pointer and as soon as that reference count reacher zero that’s when it gets delete.
Such as I creat one share pointer and copy it, so I get two share pointers, when the first one dies my reference count goes down one so I’m one now and then when the last one dies my reference count goes back to zero and I’m dead so the memory gets freed.

		std::shared_ptr<Entity> e0;
		{
			std::shared_ptr<Entity> sharedEntity = std::make_shared<Entity>();
			e0 = sharedEntity;
		}

Weak pointer

Weak pointer will not add the referenec count.

			std::weak_ptr<Entity> weakEntity = sharedEntity;

Why smart pointer?

You should probably try and use them all the time if I’m being completely honest they automate your memory management. They prevent you from accidentally leaking memory by forgetting to call delete. They realy quite useful. Shared pointer specifically has a bit of an overhead because of its reference counting systems but then again a lot of people who tend to write their own memory management systems tend to have a bit of an overhead as well.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值