According to the RAII idiom, a std::unique_ptr manages automatically and exclusively the lifetime of its resource. std::unique_ptr should be your first choice because it does its work without memory or performance overhead.
Before I show you the usage of std::unique_ptr, I will present its characteristic in a few bullet points.
- can be instantiated with and without resources.
- manages the life cycle of a single object but an array of objects.
- transparently offers the interface of the underlying resource.
- can be parametrized with its deleter function.
- can be moved (move semantic).
- can be created with the helper function std::make_unique.
The critical question of the std::unique_ptr is when to delete the underlying resource. This happens precisely when the std::unique_ptr goes out of scope or gets a new resource. Here are the two use cases.
The class MyInt (lines 7 -17) is a simple wrapper for a number. I have adjusted the destructor in lines 11 – 13 for observing the life cycle of MyInt.
I create in line 24 a std::unique_ptr and return in line 27 the address of its resource (new MyInt(1998)). Afterward, I move the uniquePtr1 to uniquePtr2 (line 29). Therefore, uniquePtr2 is the owner of the resource. That shows the output of the program in lines 30 and 31. The local std::unique_ptr in line 37 reaches the end of the scope of its valid range. Therefore, the destructor of the localPtr – that means the destructor of the resource (new MyInt(2003)) – will be executed. Here is the screenshot.
The most interesting lines are lines 42 to 44. At first, I assign the uniquePtr1 a new resource. Therefore, the destructor of MyInt(1998) will be executed. After releasing the resource in line 43, I can explicitly invoke the destructor.
The rest of the program is relatively easy to get. I create in lines 48 – 58 two std::unique_ptr and swap their resources. std::swap uses under-the-hood move semantic because std::unique_ptr supports no copy semantic. With the end of the main function, uniquePtr3 and uniquePtr4 go out of scope, and their destructor will automatically be executed.
That was the big picture. Let’s dig into a few details of std::unique_ptr.
Dealing with the lifetime of objects and arrays
std::unique_ptr has a specialization for arrays. The access is transparent. That means if the std::unique_ptr manages the lifetime of an object, the operators for the object access are overloaded (operator* and operator->); if std::unique_ptr manages the lifetime of an array, the index operator operator is overloaded. The invocations of the operators are, therefore, totally transparent and forwarded to the underlying resource.
I dereference in line 22 the std::unique_ptr and get the value of its resource.
MyStruct in lines 7 – 15 is the base of an array of std::unique_ptr’s. If I instantiate a MyStruct object, I will get its address. The destructor gives the output. Now it’s quite easy to observe the life cycle of the objects.
I create and destroy in lines 26 – 28 five instances of MyStruct. Lines 32 – 36 are more interesting. I create a MyStruct instance on the heap (line 33) and the stack (line 34). Therefore, both objects have addresses from different ranges. Afterward, I assign the local object to the std::unique_pr (line 35). Lines 40 – 54 follow a similar strategy. Now I assign the local object the first element of myUniqueArray. The index access to the std::unique_ptr in lines 35 and 43 feels like familiar index access to an array.
std::unique_ptr can have a user-supplied deleter: std::unique_ptr<int,MyDeleter> uniqPtr(new int(2011), intDeleter). The deleter is part of the type. You can use callables like functions, function objects, or lambda functions. If the deleter has no state, it will not change the size of the std::unique_ptr. If the deleter is a function object with a state or a lambda function that captures its context by value, the no-overhead principle will not hold anymore. I will write about the deleter in my post about std::shared_ptr.
Replacement for std::auto_ptr
Classical C++ already has std::auto_ptr. Its job is similar to the job of std::unique_ptr. std::auto_ptr exclusively manages the lifetime of its underlying resource. But std::auto_ptr is very strange. If you copy a std::auto_ptr, its resource will be moved. That means an operation with copy semantic performs under the hood move semantic. That’s why std::auto_ptr is deprecated, and you should instead use std::unique_ptr. std::unique_ptr can only be moved but not copied. You have to invoke std::move on a std::unique_ptr explicitly.
The graphic shows the difference between std::auto_ptr and std::unique_ptr.
If I execute the following code snippet,
the std::auto_ptr auto1 will lose its resource.
std::unique_ptr can’t be copied. Therefore, you have to use move semantics.
std::unique_ptr can be moved into the containers of the STL and afterward be used in the algorithm of the STL if they do not use copy semantics internally.
To be precise. The copying of a std::auto_ptr is undefined behavior. The moving of std::unqiue_ptr puts the source in a well-defined but not exactly specified state. But the depicted behavior is quite likely.
The helper function std::make_unique
In C++11, we have std::make_shared but not std::make_unique. This is fixed with C++14. Although Microsoft Visual Studio 2015 officially supports C++11, you can use std::make_unique. Thanks to std::make_unique, you do not have to touch new.
If you use std::make_unique in combination with automatic type deduction, your typing is reduced to its bare minimum. That proves std::unique_ptr uniqPtr2.
Always use std::make_unique
There is another subtle reason to use std::make_unique. std::make_unique is always correct.
If you use
and functionMayThrow throws, you have a memory leak with new int(2011) for this possible sequence of calls:
The next post is about std::shared_ptr. Therefore, this post was about exclusive ownership, and the next post will be about shared ownership.
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, Marco Parri Empoli, moon, and Philipp Lenk.
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|
|My special thanks to SHAVEDYAKS|
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,