C++ Move Semantics - The Complete Guide
C++ Move Semantics - The Complete Guide
About the Book
Move semantics, introduced with C++11, has become a hallmark of modern C++ programming. However, it also complicates the language in many ways. After several years of support of move semantics experienced programmers struggle with all the details of move semantics. Even for trivial classes, style guides give conflicting or inappropriate advice on how to benefit from move semantics. Time to explain all aspects of C++ move semantics in detail.
This book teaches C++ move semantics. Starting from the basic principles, it motivates and explains all the corner cases of move semantics so that as a programmer, you can use move semantics correctly. The book is valuable for those who are just starting to learn about move semantics and is essential for those who are using it already.
You will learn:
- The motivation for and terminology of move semantics
- How and why you benefit implicitly from move semantics
- How to benefit explicitly from move semantics
- All the traps involved in move semantics and how to deal with them
- All the consequences of move semantics for your programming style
As usual for books by Nicolai Josuttis, the focus lies on the application of the described features in practice. Compelling examples and useful background information help to understand and improve code, from trivial classes up to generic foundation libraries and frameworks.
Testimonials:
"Sometimes I think I have a better grasp on entanglement & quantum teleportation than I do in some weird C++ move semantics. To paraphrase Feynman: If you think you understand C++ move semantics, you don't understand C++ move semantics. Read this book." Victor Ciura
"This is the book I’ve needed for a long time." Rob Bernstein
"I thought I understood move semantics but I didn't really! I learnt a lot in your book." Jonathan Boccara
Buy early, pay less, free updates
Note that this book is published step-by-step. It started with 110 pages first published in January 2020. Since then, the content grows with new chapters, examples, and caveats about the features of move semantics and I integrate all feedback I get for the pages already published.
Currently, the book is feature complete (all language features are described).
Only the use of move semantics in the C++ standard library and the final proof reading (yes, I am not a native English writer) is missing.
See www.cppmove.com for a detailed list of covered topics.
As written, once you bought it you will get all updates for free.
There is not errata yet, but I welcome all feedback to improve the current version.
Look at http://www.cppmove.com/feedback.html.
PDF versus Other Formats
I write the book in LaTeX and generate PDF from it (the way I wrote my other books). The other formats (epub, mobi, and online reading) come from the leanpub markdown interface, for which I generate the necessary input from LaTeX by script.
Thus, the PDF layout has a better quality than the other formats. For example, the syntax highlighting rules for the formats other than PDF have to get fixed as soon as possible and the index is missing yet. Leanpub and me are working on corresponding improvements.
I hope you enjoy and benefit.
Nico
#movetcg
Bundles that include this book
Table of Contents
-
-
1. Preface
- 1.1 An Experiment
- 1.2 Versions of This Book
- 1.3 Acknowledgments
-
2. About This Book
- 2.1 What You Should Know Before Reading This Book
- 2.2 Overall Structure of the Book
- 2.3 How to Read This Book
-
2.4 The Way I Implement
- 2.4.1 Initializations
- 2.4.2 Error Terminology
- 2.4.3 Code Simplifications
- 2.5 The C++ Standards
- 2.6 Example Code and Additional Information
- 2.7 Feedback
-
1. Preface
-
I Basic Features of Move Semantics
-
3. The Power of Move Semantics
-
3.1 Motivation for Move Semantics
- 3.1.1 Example with C++03 (Before Move Semantics)
- 3.1.2 Example Since C++11 (Using Move Semantics)
-
3.2 Implementing Move Semantics
- 3.2.1 Using the Copy Constructor
- 3.2.2 Using the Move Constructor
- 3.3 Copying as a Fallback
-
3.4 Move Semantics for
const
Objects-
3.4.1
const
Return Values
-
3.4.1
- 3.5 Summary
-
3.1 Motivation for Move Semantics
-
4. Core Features of Move Semantics
-
4.1 Rvalue References
- 4.1.1 Rvalue References in Detail
- 4.1.2 Rvalue References as Parameters
-
4.2
std::move()
-
4.2.1 Header File for
std::move()
-
4.2.2 Implementation of
std::move()
-
4.2.1 Header File for
-
4.3 Moved-From Objects
- 4.3.1 Valid but Unspecified State
- 4.3.2 Reusing Moved-From Objects
- 4.3.3 Move Assignments of Objects to Themselves
-
4.4 Overloading by Different References
-
4.4.1
const
Rvalue References
-
4.4.1
- 4.5 Passing by Value
- 4.6 Summary
-
4.1 Rvalue References
-
5. Move Semantics in Classes
-
5.1 Move Semantics in Ordinary Classes
- 5.1.1 When is Move Semantics Automatically Enabled in Classes?
- 5.1.2 When Generated Move Operations Are Broken
-
5.2 Implementing Special Copy/Move Member Functions
- 5.2.1 Copy Constructor
- 5.2.2 Move Constructor
- 5.2.3 Copy Assignment Operator
- 5.2.4 Move Assignment Operator
- 5.2.5 Using the Special Copy/Move Member Functions
-
5.3 Rules for Special Member Functions
- 5.3.1 Special Member Functions
- 5.3.2 By Default, We Have Copying and Moving
- 5.3.3 Declared Copying Disables Moving (Fallback Enabled)
- 5.3.4 Declared Moving Disables Copying
- 5.3.5 Deleting Moving Makes No Sense
- 5.3.6 Disabling Move Semantics with Enabled Copy Semantics
- 5.3.7 Moving for Members with Disabled Move Semantics
- 5.3.8 Exact Rules for Generated Special Member Functions
- 5.4 The Rule of Five or Three
- 5.5 Summary
-
5.1 Move Semantics in Ordinary Classes
-
6. How to Benefit From Move Semantics
-
6.1 Avoid Objects with Names
- 6.1.1 When You Cannot Avoid Using Names
-
6.2 Avoid Unnecessary
std::move()
-
6.3 Initialize Members with Move Semantics
- 6.3.1 Initialize Members the Classical Way
- 6.3.2 Initialize Members via Moved Parameters Passed by Value
- 6.3.3 Initialize Members via Rvalue References
- 6.3.4 Compare the Different Approaches
- 6.3.5 Summary for Member Initialization
- 6.3.6 Should We Now Always Pass by Value and Move?
-
6.4 Move Semantics in Class Hierarchies
- 6.4.1 Implementing a Polymorphic Base Class
- 6.4.2 Implementing a Polymorphic Derived Class
- 6.5 Summary
-
6.1 Avoid Objects with Names
-
7. Overloading on Reference Qualifiers
-
7.1 Return Type of Getters
- 7.1.1 Return by Value
- 7.1.2 Return by Reference
- 7.1.3 Using Move Semantics to Solve the Dilemma
- 7.2 Overloading on Qualifiers
-
7.3 When to Use Reference Qualifiers
- 7.3.1 Reference Qualifiers for Assignment Operators
- 7.3.2 Reference Qualifiers for Other Member Functions
- 7.4 Summary
-
7.1 Return Type of Getters
-
8. Moved-From States
-
8.1 Required and Guaranteed States of Moved-From Objects
- 8.1.1 Required States of Moved-From Objects
- 8.1.2 Guaranteed States of Moved-From Objects
- 8.1.3 Broken Invariants
-
8.2 Destructible and Assignable
- 8.2.1 Assignable and Destructible Moved-From Objects
- 8.2.2 Non-Destructible Moved-From Objects
-
8.3 Dealing with Broken Invariants
- 8.3.1 Breaking Invariants Due to a Moved Value Member
- 8.3.2 Breaking Invariants Due to Moved Consistent Value Members
- 8.3.3 Breaking Invariants Due to Moved Pointer-Like Members
- 8.4 Summary
-
8.1 Required and Guaranteed States of Moved-From Objects
-
9. Move Semantics and
noexcept
-
9.1 Move Constructors with and without
noexcept
-
9.1.1 Move Constructors without
noexcept
-
9.1.2 Move Constructors with
noexcept
-
9.1.3 Is
noexcept
Worth It?
-
9.1.1 Move Constructors without
-
9.2 Details of
noexcept
Declarations-
9.2.1 Rules for Declaring Functions with
noexcept
-
9.2.2
noexcept
for Special Member Functions
-
9.2.1 Rules for Declaring Functions with
-
9.3
noexcept
Declarations in Class Hierarchies-
9.3.1 Checking for
noexcept
Move Constructors in Abstract Base Classes
-
9.3.1 Checking for
-
9.4 When and Where to Use
noexcept
- 9.5 Summary
-
9.1 Move Constructors with and without
-
10. Value Categories
-
10.1 Value Categories
- 10.1.1 History of Value Categories
- 10.1.2 Value Categories Since C++11
- 10.1.3 Value Categories Since C++17
-
10.2 Special Rules for Value Categories
- 10.2.1 Value Category of Functions
- 10.2.2 Value Category of Data Members
-
10.3 Impact of Value Categories When Binding References
- 10.3.1 Overload Resolution with Rvalue References
- 10.3.2 Overloading by Reference and Value
- 10.4 When Lvalues become Rvalues
- 10.5 When Rvalues become Lvalues
-
10.6 Checking Value Categories with
decltype
-
10.6.1 Using
decltype
to Check the Type of Names -
10.6.2 Using
decltype
to Check the Value Category
-
10.6.1 Using
- 10.7 Summary
-
10.1 Value Categories
-
3. The Power of Move Semantics
-
II Move Semantics in Generic Code
-
11. Perfect Forwarding
-
11.1 Motivation for Perfect Forwarding
- 11.1.1 What we Need to Perfectly Forward Arguments
-
11.2 Implementing Perfect Forwarding
- 11.2.1 Universal (or Forwarding) References
-
11.2.2
std::forward<>()
- 11.2.3 The Effect of Perfect Forwarding
-
11.3 Rvalue References versus Universal References
- 11.3.1 Rvalue References of Actual Types
- 11.3.2 Rvalue References of Function Template Parameters
-
11.4 Overload Resolution with Universal References
- 11.4.1 Fixing Overload Resolution with Universal References
- 11.5 Perfect Forwarding in Lambdas
- 11.6 Summary
-
11.1 Motivation for Perfect Forwarding
-
12. Tricky Details of Perfect Forwarding
-
12.1 Universal References as Non-Forwarding References
-
12.1.1 Universal References and
const
- 12.1.2 Universal References in Detail
- 12.1.3 Universal References of Specific Types
-
12.1.1 Universal References and
-
12.2 Universal or Ordinary Rvalue Reference?
- 12.2.1 Rvalue References of Members of Generic Types
- 12.2.2 Rvalue References of Parameters in Class Templates
- 12.2.3 Rvalue References of Parameters in Full Specializations
-
12.3 How the Standard Specifies Perfect Forwarding
- 12.3.1 Explicit Specification of Types for Universal References
- 12.3.2 Conflicting Template Parameter Deduction with Universal References
- 12.3.3 Pure RValue References of Generic Types
-
12.4 Nasty Details of Perfect Forwarding
- 12.4.1 “Universal” versus “Forwarding” Reference
-
12.4.2 Why
&&
for Both Ordinary Rvalues and Universal References?
- 12.5 Summary
-
12.1 Universal References as Non-Forwarding References
-
13. Perfect Passing with
auto&&
-
13.1 Default Perfect Passing
- 13.1.1 Default Perfect Passing in Detail
-
13.2 Universal References with
auto&&
-
13.2.1 Type Deduction of
auto&&
-
13.2.2 Perfectly Forwarding an
auto&&
Reference
-
13.2.1 Type Deduction of
-
13.3
auto&&
as Non-Forwarding Reference-
13.3.1 Universal References and the Range-Based
for
Loop
-
13.3.1 Universal References and the Range-Based
- 13.4 Perfect Forwarding in Lambdas
-
13.5 Using
auto&&
in C++20 Function Declarations - 13.6 Summary
-
13.1 Default Perfect Passing
-
14. Perfect Returning with
decltype(auto)
- 14.1 Perfect Returning
-
14.2
decltype(auto)
-
14.2.1 Return Type
decltype(auto)
- 14.2.2 Deferred Perfect Returning
- 14.2.3 Perfect Forwarding and Returning with Lambdas
-
14.2.1 Return Type
- 14.3 Summary
-
11. Perfect Forwarding
-
III Move Semantics in the C++ Standard Library
-
15. Move-Only Types
-
15.1 Declaring and Using Move-Only Types
- 15.1.1 Declaring Move-Only Types
- 15.1.2 Using Move-Only Types
- 15.1.3 Passing Move-Only Objects as Arguments
- 15.1.4 Returning Move-Only Objects by Value
- 15.1.5 Moved-From States of Move-Only Objects
- 15.2 Summary
-
15.1 Declaring and Using Move-Only Types
-
16. Moving Algorithms and Iterators
- 16.1 Moving Algorithms
- 16.2 Removing Algorithms
-
16.3 Move Iterators
- 16.3.1 Move Iterators in Algorithms
- 16.3.2 Move Iterators in Constructors and Member Functions
- 16.4 Summary
-
17. Move Semantics in Types of the C++ Standard Library
-
17.1 Move Semantics for Strings
- 17.1.1 String Assignments and Capacity
-
17.2 Move Semantics for Containers
- 17.2.1 Basic Move Support for Containers as a Whole
- 17.2.2 Insert and Emplace Functions
-
17.2.3 Move Semantics for
std::array<>
-
17.3 Move Semantics for Vocabulary Types
- 17.3.1 Move Semantics for Pairs
-
17.3.2 Move Semantics for
std::optional<>
-
17.4 Move Semantics for Smart Pointers
-
17.4.1 Move Semantics for
std::shared_ptr<>
-
17.4.2 Move Semantics for
std::unique_ptr<>
-
17.4.1 Move Semantics for
-
17.5 Move Semantics for IOStreams
- 17.5.1 Moving IOStream Objects
- 17.5.2 Using Temporary IOStreams
-
17.6 Move Semantics for Multithreading
-
17.6.1
std::thread<>
andstd::jthread<>
- 17.6.2 Futures, Promises, and Packaged Tasks
-
17.6.1
- 17.7 Summary
-
17.1 Move Semantics for Strings
-
18. Glossary
-
18.1 C
- 18.1.1 CPP file
-
18.2 F
- 18.2.1 forwarding reference
- 18.2.2 full specialization
-
18.3 G
- 18.3.1 glvalue
-
18.4 H
- 18.4.1 header file
-
18.5 I
- 18.5.1 include file
- 18.5.2 incomplete type
-
18.6 L
- 18.6.1 lvalue
-
18.7 N
- 18.7.1 named return value optimization (NRVO)
-
18.8 P
- 18.8.1 prvalue
-
18.9 R
- 18.9.1 return value optimization (RVO)
- 18.9.2 rvalue
-
18.10 S
- 18.10.1 small/short string optimization (SSO)
-
18.11 T
- 18.11.1 translation unit
-
18.12 U
- 18.12.1 universal reference
-
18.13 V
- 18.13.1 value category
- 18.13.2 variadic template
-
18.14 X
- 18.14.1 xvalue
-
18.1 C
-
15. Move-Only Types
- Notes
The Leanpub 60-day 100% Happiness Guarantee
Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.
See full terms
Do Well. Do Good.
Authors have earned$11,577,045writing, publishing and selling on Leanpub, earning 80% royalties while saving up to 25 million pounds of CO2 and up to 46,000 trees.
Learn more about writing on Leanpub
Free Updates. DRM Free.
If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).
Most Leanpub books are available in PDF (for computers), EPUB (for phones and tablets) and MOBI (for Kindle). The formats that a book includes are shown at the top right corner of this page.
Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.
Learn more about Leanpub's ebook formats and where to read them
Top Books
Recipes for Decoupling
Matthias NobackSignalR on .NET 6 - the Complete Guide
Fiodar SazanavetsLearn everything there is to learn about SignalR and how to integrate it with the latest .NET 6 and C# 10 features. Learn how to connect any type of client to SignalR, including plain WebSocket client. Learn how to build interactive applications that can communicate with each other in real time without making excessive calls.
The BDD Books - Discovery (Japanese Edition)
Gáspár Nagy, Seb Rose, and Yuya Kazamaウクライナ難民を支援 - 2022年5月末まで延長!
この本の売り上げの50%は、 https://unicef.hu/veszhelyzet-ukrajnaban と https://int.depaulcharity.org/fundraising-for-depaul-ukraine/ に寄付されます。
本書籍は、振る舞い駆動開発(Behavior Driven Development, BDD)や受け入れテスト駆動開発(Acceptance Test-Driven Development, ATDD)の発見フェーズを最大限に活用する方法を提供します。
The easiest way to learn design patterns
Fiodar SazanavetsLearn design patterns in the easiest way possible. You will no longer have to brute-force your way through each one of them while trying to figure out how it works. The book provides a unique methodology that will make your understanding of design patterns stick. It can also be used as a reference book where you can find design patterns in seconds.
Agile Testing Condensed Japanese Edition
Yuya Kazama, Janet Gregory, and Lisa CrispinJanet GregoryとLisa Crispinによる2019年9月発行の書籍『Agile Testing Condensed』の日本語翻訳版です。アジャイルにおいてどのような考えでテストを行うべきなのか簡潔に書かれています!
OpenIntro Statistics
David Diez, Christopher Barr, Mine Cetinkaya-Rundel, and OpenIntroA complete foundation for Statistics, also serving as a foundation for Data Science.
Leanpub revenue supports OpenIntro (US-based nonprofit) so we can provide free desk copies to teachers interested in using OpenIntro Statistics in the classroom and expand the project to support free textbooks in other subjects.
More resources: openintro.org.
Tech Giants in Healthcare
Dr. Bertalan MeskoThis comprehensive guide, Tech Giants in Healthcare, clarifies how and why big tech companies step into healthcare, and breaks it down from one market player to the other in what direction they are going, what tools they are using and what horizons they have in front of them.
Functional event-driven architecture: Powered by Scala 3
Gabriel VolpeExplore the event-driven architecture (EDA) in a purely functional way, mainly powered by Fs2 streams in Scala 3!
Leverage your functional programming skills by designing and writing stateless microservices that scale, powered by stateful message brokers.
CCIE Service Provider Version 4 Written and Lab Exam Comprehensive Guide
Nicholas RussoThe service provider landscape has changed rapidly over the past several years. Networking vendors are continuing to propose new standards, techniques, and procedures for overcoming new challenges while concurrently reducing costs and delivering new services. Cisco has recently updated the CCIE Service Provider track to reflect these changes; this book represents the author's personal journey in achieving that certification.
Ansible for DevOps
Jeff GeerlingAnsible is a simple, but powerful, server and configuration management tool. Learn to use Ansible effectively, whether you manage one server—or thousands.
Top Bundles
- #1
All the Books of The Medical Futurist
6 Books
We put together the most popular books from The Medical Futurist to provide a clear picture about the major trends shaping the future of medicine and healthcare. Digital health technologies, artificial intelligence, the future of 20 medical specialties, big pharma, data privacy, digital health investments and how technology giants such as Amazon... - #2
Practical FP in Scala + Functional event-driven architecture
2 Books
Practical FP in Scala (A hands-on approach) & Functional event-driven architecture, aka FEDA, (Powered by Scala 3), together as a bundle! The content of PFP in Scala is a requirement to understand FEDA so why not take advantage of this bundle!? - #3
Software Architecture for Developers: Volumes 1 & 2 - Technical leadership and communication
2 Books
"Software Architecture for Developers" is a practical and pragmatic guide to modern, lightweight software architecture, specifically aimed at developers. You'll learn:The essence of software architecture.Why the software architecture role should include coding, coaching and collaboration.The things that you really need to think about before... - #4
CCIE Service Provider Ultimate Study Bundle
2 Books
Piotr Jablonski, Lukasz Bromirski, and Nick Russo have joined forces to deliver the only CCIE Service Provider training resource you'll ever need. This bundle contains a detailed and challenging collection of workbook labs, plus an extensively detailed technical reference guide. All of us have earned the CCIE Service Provider certification... - #6
Pattern-Oriented Memory Forensics and Malware Detection
2 Books
This training bundle for security engineers and researchers, malware and memory forensics analysts includes two accelerated training courses for Windows memory dump analysis using WinDbg. It is also useful for technical support and escalation engineers who analyze memory dumps from complex software environments and need to check for possible... - #8
Modern C++ Collection
3 Books
Get All about Modern C++C++ Standard Library, including C++20Concurrency with Modern C++, including C++20C++20Each book has about 200 complete code examples. Updates are included. When I update one of the books, you immediately get the updated bundle. You can expect significant updates to each new C++ standard (C++23, C++26, .. ) and also...