Using smart pointers

I have a project and I want to use smart pointers better.

The main idea is to use them when returning a new object from a function. The question is which smart pointer to use? auto_ptr or shared_ptr from boost? As I know, auto_ptr is slower, but it can return to "clean" pointers.

And if I use a smart pointer where I do not need it, will it make it slower?

+3
source share
5 answers

What makes you think auto_ptrslower than shared_ptr? Normally, I would expect the opposite to be true, since shared_ptrit is necessary to update the reference count.

According to what you should use, different smart pointers imply different semantics of ownership. Ownership implies responsibility for the removal of an object when it is no longer needed.

  • A raw pointer implies a lack of ownership ; a program that correctly uses smart pointers can still use raw pointers in many places where the property is not intended (for example, if you need to pass an optional object reference to a function, you will often use a raw pointer).
  • scoped_ptr (.. ), .
  • auto_ptr (.. ) . , , ( ). auto_ptr - , - , auto_ptr , ( , ).
  • unique_ptr , auto_ptr, ++ 0x ( rvalue), ( ), auto_ptr. , unique_ptr , auto_ptr.
  • shared_ptr . -, . , .

, shared_ptr STL, (- ). shared_ptr, . ( ) - boost (ptr_vector, ptr_map ..), ( ) , ( ) ) .

: , , , . , , , .

[, unique_ptr]

+11

, shared_ptr<>. , , . , , .

, , . , , .

+2

shared_ptr, auto_ptr , . , STL, shared_ptr.

, , .

+1

.
, auto_ptr, .
auto_ptr .
auto_ptr , .
, , . , .
, , -, shared_pointer

+1

shared_ptr. auto_ptr . auto_ptr , , shared_ptr.

, , .

auto_ptr .

auto_ptr , , , .

auto_ptr a_ptr ( someClass);

auto_ptr another_ptr = aptr;// another_ptr , a_ptr !

auto_ptr.

, , , . 1 , .

. ( A B A shared_ptr, B B, B- shared_ptr, A), A B , .

shared_ptr, , weak_ptr. . http://www.boost.org/doc/libs/1_45_0/libs/smart_ptr/smart_ptr.htm

0

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


All Articles