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!
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.
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.
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.
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.
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.
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>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With