After I draw the big picture of a std::shared_ptr in the last post, I want to present two special aspects of this smart pointer in this post. First, I show with std::shared_from_this how to create a std::shared_ptr from an object; second, I’m interested in the question to the answer: Should a function take a std::shared_ptr by copy or by reference? The numbers are quite interesting.
std::shared_ptr from this
Thanks to std::enable_shared_from_this, you can create an object that returns a std::shared_ptr from this. Therefore, the class of the objects has to be public derived from std::enable_shared_from_this. Now, you have the method shared_from_this available, which you can use to create std::shared_ptr from this.
The program shows the theory in practice.
The smart pointer shareMe (line 17) and it copies shareMe1 (line 18) and shareMe2 (line 20) reference the very same resource and increment and decrement the reference counter.
The call shareMe->getShared() in line 18 creates a new smart pointer. getShared() internally uses (line 9) the function shared_from_this.
There is something very special about the class ShareMe.
Curiously recurring template pattern
ShareMe is the derived class and type argument (line 6) of the base class std::enabled_shared_from_this. This pattern is called CRTP, an abbreviation for Curiously Recurring Template Pattern. Obviously, there is no recursion because the base class methods will be instantiated when they are called. CRTP is an often-used idiom in C++ to implement static polymorphism. Unlike dynamic polymorphism with virtual run-time methods, static polymorphism occurs at compile time.
But now, back to the std::shared_ptr.
std::shared_ptr as a function argument
Therefore, we are dealing with a quite interesting question. Should a function take its std::shared_ptr by a copy of by reference? But first. Why should you care? Does it matter if a function takes its std::shared_ptr by copy or reference? Under the hood, all is a reference. My definite answer is yes, and no. Semantically, it makes no difference. From the performance perspective, it makes a difference.
The function byReference (line 6 – 8) and byCopy (line 10 – 12) takes their std::shared_ptr by reference and copy. The output of the program emphasizes the critical point.
The function byCopy takes its std::shared_ptr by copy. Therefore, the reference count increases in the function body to 2 and decreases to 1. The question is now. How expensive is the incrementing and decrementing of the reference counter? Because incrementing the reference counter is an atomic operation, I expect a measurable difference. To be precise. The incrementing of the reference counter is an atomic operation with relaxed semantics; the decrementing is an atomic operation with acquire-release semantics.
Let’s have a look at the numbers.
My Linux PC is more powerful than my Windows PC. Therefore, you must read the absolute numbers with a grain of salt. I use GCC 4.8 and Microsoft Visual Studio 15. Additionally, I translate the program with maximum and without optimization. At first, my small test program.
In the test program, I hand over the std::shared_ptr by reference and copying and using the std::shared_ptr to initialize another std::shared_ptr. This was the most straightforward scenario to cheat the optimizer. I invoke each function 100 million times.
First, the program is without optimization.
And now, the one with maximum optimization.
With maximum optimization
The raw numbers of the program performanceCopyShared.cpp speak a clear message.
- The perReference function is about two times faster than its pendant perCopy, with maximum optimization on Linux about five times faster.
- Maximum optimization gives Windows a performance boost of 3; on Linux by a factor of 30 – 80.
- The Windows application is without optimization faster than the Linux application. That’s interesting because my Windows PC is slower.
The classical issue of smart pointers using reference count is to have cyclic references. Therefore, std::weak_ptr comes to our rescue. I will have in the next post a closer look at std::weak_ptr and show you how to break cyclic references.
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,