Using C ++ 11 Smart Pointer

I have a question about smart pointers in C ++ 11. I started looking at C ++ 11 (I usually programmed in C #) and read something about smart pointers. Now I have a question, do smart pointers completely replace the "old" style of pointers, should I always use them?

unique_ptr to solve all memory management issues in C ++, or am I mistaken?

For instance:

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

It seems much smarter than:

 auto *game2 = new GameManager(); game2->Start(); delete game2; 

Thanks, I'm a little confused!

+6
source share
4 answers

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

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

They eliminate many possible programming errors and reduce the complexity of creating the right code with pointers.

To go even further is considered good to change

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

To:

 std::unique_ptr<GameManager> game (std::make_unique<GameManager>()); 
+6
source

For the use shown, while unique_ptr better than a raw pointer, since it indicates the ownership of allocated resources, you probably shouldn't use any pointer at all. Instead, simply declare a local file:

 GameManager game; game.Start(); 

This may not be enough if ownership can be transferred to something else, while ownership of unique_ptr can be easily transferred.

+9
source

In addition to the unique_ptr owner of unique_ptr there are also situations where there is a common or difficult to determine ownership. In these cases, shared_ptr provides reference counting, and the last owner removes the referent.

In cases where shared_ptr can be involved in a complex reference loop, the standard also provides weak_ptr .

All this replaces the older auto_ptr .

+3
source

No, do not completely replace all raw pointers.

The use of smart pointers (unique_ptr, shared_ptr) is really useful only for those pointers that own and manage pointer memory. However, if a function takes a pointer as a parameter, then you do not want to transfer ownership. The function just needs access to the pointer.

 void ShowCredits(GameManager* game) // Just use game, don't take ownership. { // A raw pointer here is good. // ... } void main() { auto game = make_unique<GameManager>(); // game owns the GameManager. game->Start(); ShowCredits(game.get()); } 

PS If ShowCredits relies on a game that is always active (that is, it may not necessarily be nullptr), then you might be better off if the parameter is of type GameManager &.

+3
source

Source: https://habr.com/ru/post/975933/


All Articles