Will shared_ptr automatically free memory?

I need to use shared_ptr here because I cannot change the API.

Foo1 *foo1 = new Foo1(...); shared_ptr<Foo2> foo2(foo1); 

Will shared_ptr work with freeing the memory used by foo1? If I understood correctly, I would not need to correctly call delete on foo1?

+4
source share
3 answers

Yes. You are correct, but the correct way to initialize foo2 :

 std::shared_ptr<Foo2> foo2 = std::make_shared<Foo1>(); 

Herb Sutter discusses the reasons why you should use std::make_shared<>() here: http://herbsutter.com/gotw/_103/

+11
source

You should not call delete on foo1.

Better not to create foo1. Only foo2:

 shared_ptr<Foo2> foo2(new Foo1(...)); 

std :: shared_ptr is a smart pointer that keeps sharing an object through a pointer.

If you don't need this pointer for sharing, consider using std::unique_ptr

std :: unique_ptr is a smart pointer that: retains the sole ownership of the object through the pointer and destroys the object with the pointer when unique_ptr goes beyond.

+3
source

Right. Smart pointers provide semantics of ownership. In particular, the semantics provided by std::shared_ptr are such that the object will be deleted after the destruction of the last shared_ptr pointing to it. shared_ptr stores a reference counter (the number of shared_ptr refers to the object), and when it reaches 0, it deletes the object.

+1
source

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


All Articles