Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ 11 Smart Pointer usage

I have a question about smart pointers in c++ 11. I've started to have a look at C++ 11 (I usualy program in c#) and read some thing about smart pointers. Now i have the question, does smart pointers completely replace the "old" style of pointers, should i always use them?

The unique_ptr seems to solve all problems with memory management in C++, or am i wrong?

For example:

std::unique_ptr<GameManager> game (new GameManager());

game->Start();

Seems to be much smarter than:

auto *game2 = new GameManager();

game2->Start();

delete game2;

Thank you, i am a little bit confused!

like image 568
BendEg Avatar asked Sep 27 '14 16:09

BendEg


People also ask

What are smart pointers used for?

Smart pointers are used to make sure that an object is deleted if it is no longer used (referenced). The unique_ptr<> template holds a pointer to an object and deletes this object when the unique_ptr<> object is deleted.

What is a smart pointer in C?

Smart pointers in C++ A pointer is used to store the address of another variable. In other words, a pointer extracts the information of a resource that is outside the program (heap memory). We use a copy of the resource, and to make a change, it is done in the copied version.

When should I use shared_ptr?

Use shared_ptr if you want to share ownership of a resource. Many shared_ptr can point to a single resource. shared_ptr maintains reference count for this propose. when all shared_ptr's pointing to resource goes out of scope the resource is destroyed.

How many types of smart pointers are there in C++?

C++11 has introduced three types of smart pointers, all of them defined in the <memory> header from the Standard Library: std::unique_ptr — a smart pointer that owns a dynamically allocated resource; std::shared_ptr — a smart pointer that owns a shared dynamically allocated resource.


2 Answers

For the usage shown, while the unique_ptr is better than a raw pointer as it indicates ownership of the allocated resources, you probably shouldn't use any kind of pointer at all. Instead just declare a local:

GameManager game;
game.Start();

This may not suffice if the ownership may have to be given to something else, whereas the ownership of a unique_ptr can easily be transferred.

like image 157
Michael Urman Avatar answered Sep 20 '22 06:09

Michael Urman


To answer your question: yes, they do solve memory management problems.

It is considered good style to use them as much as possible.

They eliminate many possible programming errors, and reduce the difficulty of creating correct code with pointers.

To go even further, it is considered good to change

std::unique_ptr<GameManager> game (new GameManager());

To:

std::unique_ptr<GameManager> game (std::make_unique<GameManager>());
like image 32
Michael Gazonda Avatar answered Sep 23 '22 06:09

Michael Gazonda