Unique pointer
- If it goes out of the scope, it will be destroyed.
- Can not copy it.
- 만약에 복사가 됐다면, 두개가 같은걸 바라보는데, 하나가 사라지면 다 사라지니까 그 자체가 말이 안된다.
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>();
// std::unique_ptr<Entity> e0 = entity // it doesn't work. (not unique!)
entity->Print();
// if it goes out of this scope ( "{}" ), then it is destroyed.
}
}
Shared pointer
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> sharedEntity = std::make_shared<Entity>);
std::shared_ptr<Entity> e0 = sharedEntity // works fine!
entity->Print();
}
}
Weak pointer
- if you copy the shared pointer to shared pointer, then pointer count increase
- if you copy the shared pointer to weak pointer, then pointer count doesn’t increase
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> sharedEntity = std::make_shared<Entity>);
std::weak_ptr<Entity> weak_ptr = sharedEntity // works fine!
entity->Print();
}
}