Smart pointers. When, where and how?

First, since there are different types of smart pointers, I would like to focus this question on two of them: links counted by intrusive and non-intrusive smart pointers. The question is asked individually for each type of pointer.

I am not quite sure how to formulate my question, so here is what I am not asking: I am not asking why or when smart pointers are needed. Not the type of smart pointer I should use and for what.

This is what I ask, and I hope this is clear enough: when you are dealing with objects with smart controls, in what contexts should I use pointer semantics? That is, the semantics of smart pointers, the semantics of the original pointer, something else (for example, a reference to a smart pointer)?

Obviously, when I "store" a pointer to an object (an object that is a reference object of counted memory), such as a global pointer or as a member of a class, it should be a smart pointer, so it would require but what about other situations?

When I pass a pointer as an argument to a function, should it be a smart pointer, a raw pointer, a reference to a smart pointer, or maybe something else? What about returned pointers? Local pointers? etc...

Of course, I could use smart pointers everywhere, which is the safest option, but I feel like it really is not needed and adds overhead.

+3
source share
7 answers

IMHO, sometimes it's better to do something faster than a slight performance improvement. I believe that you will do something faster if you always use smart pointers.

My suggestion: use smart pointers everywhere. Then use the profiler to see if it creates significant overhead. Where does he do it, change it :)

+5
source

, . , , , Java #, , . ++ .

+4

tyring, " " " ", , " " . . boost::scoped_ptr boost::shared_ptr , bwteeen boost::shared_ptr T*

"" , . ( "" ), , . : . , , . , , , , . - NULL, .

, , . , .

+2

:

  • : (const)
  • (, ): shared_ptr
  • , (): weak_ptr
  • : scoped_ptr
  • (output-parameter,...): raw pointer
+2

/ . STL auto_ptr try/catch. . , " , ". , . , , - .

+1

, , ( , ) . "" .

, " ", , ....

0
"When I'm passing a pointer as a function argument, should it be a smart-pointer, a raw
pointer, a reference to a smart pointer, or maybe something else? What about returned
pointers? Local pointe rs? so on..."

my 2p, shared_ptrs, :

,

,

scoped_ptr

0

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


All Articles