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.