std::shared_ptr’s share the resource. The shared reference counter counts the number of owners. Copying a std::shared_ptr increases the reference count by one. Destroying a std::shared_ptr decreases the reference count by one. If the reference count becomes zero, the resource will automatically be released.
Before I deal with the details of the std::shared_ptr, I will bring you on the same page and explain the basics.
Copying a std::shared_ptr increases the reference count by one. Both smart pointers use the same resource afterwards. I depicted this scenario.
Thanks to shared1 shared2 are initialized. Ultimately, the reference count is 2, and both smart pointers have the same resource.
The program shows the typical usage of smart pointers. To get a visual idea of the life cycle of the resource, I put a short message in the constructor and destructor of MyInt (lines 8 – 16).
Here is the screenshot of the program.
I create in line 22 MyInt(1998). This is the resource the smart pointer should take care of. By using sharPtr->val I have direct access to the resource (line 23). The output of the program shows the numbers of the reference counter. It starts in line 24 with one, becomes by the local copy shartPtr in line 28 two, and goes after the block (lines 27 – 40) back to one. As a reset call, the copy assignment in line 33 modifies the reference counter. The expression sharPtr= shared_ptr<MyInt>(new MyInt(2011)) in line 38 is more interesting. Firstly, the resource MyInt(2011) is created and assigned to sharPtr. Consequently, the destructor of sharPtr is invoked. sharedPtr was the exclusive owner of the resource new MyInt(1998) (line 22). The last resource new MyInt(2011), will be destroyed at the end of the main.
The program should not be too challenging. Now we can dig deeper.
The control block
The std::shared_ptr‘s share is more than a resource and a reference counter. They share a resource and a control block. The control block has two counters and, eventually, more data. Two counters? The control block has a counter for the std::shared_ptr and the std::weak_ptr referencing the std::shared_ptr. That’s the first time I’m speaking about the std::weak_ptr. Their job is to break cyclic references. I will write a separate post about cyclic references. Once more, the overview.
The control block has
- a counter for the std::shared_ptr.
- a counter for the std::weak_ptr.
- eventually further data like a special deleter or an allocator.
If you create std::shared_ptr together with its resource, two allocations are necessary. One for the resource and one for the control block. std::make_shared makes one allocation out of the two and is, therefore, faster (see: Memory and performance overhead of smart pointers) and safe. You do not have this safety guarantee for std::shared_ptr<int>(new int(2011)). If you create a smart pointer with std::shared_ptr<int>(new int(2011)), one of the allocations may fail, and you have a memory leak.
A special deleter can parametrize the std::shared_ptr. Exactly that happens in the next section of this post.
The deleter of the std::shared_ptr is opposite to that of a std::unique_ptr, not a component of the type. Therefore, you can easily push std::shared_ptr with different deleters onto a std::vector<std::shared_ptr<int>>. The special deleter will be stored in the control block.
I create in the next example a special std::shared_ptr that logs how much memory has already been released.
Deleter in lines 8 – 27 is the special deleter. The type T. parametrizes the deleter It counts with the static variable count (line 23), how often the call operator (lines 11 – 14) was used. Deleter returns all the information with getInfo (lines 15 – 21). The function createRandomNumbers (line 32 – 42) creates between 1 to 1000 std::shared_ptr (line 40) parametrized by the special deleter intDeleter().
The first usage of intDeleter->getInfo() shows that no resource has been released. This changes with the call sharedPtr2.reset() in line 53. An int variable with 4 bytes has been released. The call createRandomNumbers() in line 57 creates 74 std::shared_ptr<int>. Of course, you can use the deleter for a std::unique_ptr (lines 60 – 68). The memory for the double objects will be released after the end of the block in line 68.
std::shared_ptr has a lot more to offer. You can create a std:.shared_ptr to an already existing object. std::shared_ptr has minimum multithreading guarantees. But one question is still not answered. Should your function take a std::shared_ptr by value or by reference? Get the answers in the next post.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, and Marco Parri Empoli.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,