S
S
sabn1k2016-03-09 19:42:01
C++ / C#
sabn1k, 2016-03-09 19:42:01

Where should smart pointers be used?

Greetings.
Actually, I started reading a book on STL, first there is a brief overview of C ++ 11.
I really liked smart pointers. When should you use them and which one? Is it necessary, for example, to declare an array with std::unique_ptr , etc.
Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stanislav Makarov, 2016-03-09
@Nipheris

When to use them

Smart pointers? - asked this morning.
In most cases, std::array is better for arrays of size known at compile time, and std::vector if the size is only known at run time. An exception is the need to interact with code that uses ordinary pointers to arrays (in particular, with Cish code).
std::unique_ptr implies one owner at a time, and ownership transfer from one smart pointer to another (ownership transfer). std::shared_ptr uses reference counting so that an object has multiple owners. The object will be destroyed when the last shared_ptr pointing to this object is destroyed.
Of course, both strategies work only in smart pointers. If you copy the contents of a smart pointer into a smart pointer and then the object is deleted by the smart pointer, the smart pointer will continue to point to the same address in memory. This is an obvious thing, but that's what everyone runs into at first.
Separately, I will add that unique_ptr is one of the waysobject composition modeling (when the owning object dies, those owned by it die), and shared_ptr - aggregations (if the owning object dies, those owned by it continue to live until someone else needs them).

O
Oleg Tsilyurik, 2016-03-09
@Olej

Actually, I started reading a book on STL, first there is a brief overview of C ++ 11.
I really liked smart pointers. When should you use them and which one?

You have to be careful with smart pointers. They are not always appropriate. And they are not an integral part of the STL and did not lie next to the STL in any way.
Here is an opinion :
It was not an easy lot for those who connected their lives with programming in the C++ language. In my opinion, the most beautiful C language has been mutilated to make C++ . Moreover, C++ mutates almost every quarter, gradually turning into a transformer toy, and the author of C++ himself is forced to publish one book after another to interpret his brainchild. With the introduction of the C++ language into commercial development, the reliability of the software fell sharply, which users felt the hard way. The excessive redundancy of the C++ language has led to the fact that each programmer encodes the same algorithm in his own way and, in accordance with the laws of Murphy and Peters, not in the most optimal way.
This applies to a very significant extent to smart pointers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question