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.
"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.
- An Experiment
- Versions of This Book
About This Book
- What You Should Know Before Reading This Book
- Overall Structure of the Book
- How to Read This Book
The Way I Implement
- Error Terminology
- Code Simplifications
- The C++ Standards
- Example Code and Additional Information
I Basic Features of Move Semantics
1. The Power of Move Semantics
1.1 Motivation for Move Semantics
- 1.1.1 Example with C++03 (Before Move Semantics)
- 1.1.2 Example Since C++11 (Using Move Semantics)
1.2 Implementing Move Semantics
- 1.2.1 Using the Copy Constructor
- 1.2.2 Using the Move Constructor
- 1.3 Copying as a Fallback
1.4 Move Semantics for
- 1.5 Summary
- 1.1 Motivation for Move Semantics
2. Core Features of Move Semantics
2.1 Rvalue References
- 2.1.1 Rvalue References in Detail
- 2.1.2 Rvalue References as Parameters
2.2.1 Header File for
2.2.2 Implementation of
- 2.2.1 Header File for
2.3 Moved-From Objects
- 2.3.1 Valid but Unspecified State
- 2.3.2 Reusing Moved-From Objects
- 2.3.3 Move Assignments of Objects to Themselves
2.4 Overloading by Different References
- 2.5 Passing by Value
- 2.6 Summary
- 2.1 Rvalue References
3. Move Semantics in Classes
3.1 Move Semantics in Ordinary Classes
- 3.1.1 When is Move Semantics Automatically Enabled in Classes?
- 3.1.2 When Generated Move Operations Are Broken
3.2 Implementing Special Copy/Move Member Functions
- 3.2.1 Copy Constructor
- 3.2.2 Move Constructor
- 3.2.3 Copy Assignment Operator
- 3.2.4 Move Assignment Operator
- 3.2.5 Using the Special Copy/Move Member Functions
3.3 Rules for Special Member Functions
- 3.3.1 Special Member Functions
- 3.3.2 By Default, We Have Copying and Moving
- 3.3.3 Declared Copying Disables Moving (Fallback Enabled)
- 3.3.4 Declared Moving Disables Copying
- 3.3.5 Deleting Moving Makes No Sense
- 3.3.6 Disabling Move Semantics with Enabled Copy Semantics
- 3.3.7 Moving for Members with Disabled Move Semantics
- 3.3.8 Exact Rules for Generated Special Member Functions
- 3.4 The Rule of Five or Three
- 3.5 Summary
- 3.1 Move Semantics in Ordinary Classes
4. How to Benefit From Move Semantics
4.1 Avoid Objects with Names
- 4.1.1 When You Cannot Avoid Using Names
4.2 Avoid Unnecessary
4.3 Initialize Members with Move Semantics
- 4.3.1 Initialize Members the Classical Way
- 4.3.2 Initialize Members via Moved Parameters Passed by Value
- 4.3.3 Initialize Members via Rvalue References
- 4.3.4 Compare the Different Approaches
- 4.3.5 Summary for Member Initialization
- 4.3.6 Should We Now Always Pass by Value and Move?
4.4 Move Semantics in Class Hierarchies
- 4.4.1 Implementing a Polymorphic Base Class
- 4.4.2 Implementing a Polymorphic Derived Class
- 4.5 Summary
- 4.1 Avoid Objects with Names
5. Overloading on Reference Qualifiers
5.1 Return Type of Getters
- 5.1.1 Return by Value
- 5.1.2 Return by Reference
- 5.1.3 Using Move Semantics to Solve the Dilemma
- 5.2 Overloading on Qualifiers
5.3 When to Use Reference Qualifiers
- 5.3.1 Reference Qualifiers for Assignment Operators
- 5.3.2 Reference Qualifiers for Other Member Functions
- 5.4 Summary
- 5.1 Return Type of Getters
6. Moved-From States
6.1 Required and Guaranteed States of Moved-From Objects
- 6.1.1 Required States of Moved-From Objects
- 6.1.2 Guaranteed States of Moved-From Objects
- 6.1.3 Broken Invariants
6.2 Destructible and Assignable
- 6.2.1 Assignable and Destructible Moved-From Objects
- 6.2.2 Non-Destructible Moved-From Objects
6.3 Dealing with Broken Invariants
- 6.3.1 Breaking Invariants Due to a Moved Value Member
- 6.3.2 Breaking Invariants Due to Moved Consistent Value Members
- 6.3.3 Breaking Invariants Due to Moved Pointer-Like Members
- 6.4 Summary
- 6.1 Required and Guaranteed States of Moved-From Objects
7. Move Semantics and
7.1 Move Constructors with and without
7.1.1 Move Constructors without
7.1.2 Move Constructors with
- 7.1.1 Move Constructors without
7.2 Details of
7.2.1 Rules for Declaring Functions with
noexceptfor Special Member Functions
- 7.2.1 Rules for Declaring Functions with
noexceptDeclarations in Class Hierarchies
7.3.1 Checking for
noexceptMove Constructors in Abstract Base Classes
- 7.3.1 Checking for
7.4 When and Where to Use
- 7.5 Summary
- 7.1 Move Constructors with and without
8. Value Categories
8.1 Value Categories
- 8.1.1 History of Value Categories
- 8.1.2 Value Categories Since C++11
- 8.1.3 Value Categories Since C++17
8.2 Special Rules for Value Categories
- 8.2.1 Value Category of Functions
- 8.2.2 Value Category of Data Members
8.3 Impact of Value Categories When Binding References
- 8.3.1 Overload Resolution with Rvalue References
- 8.3.2 Overloading by Reference and Value
- 8.4 When Lvalues become Rvalues
- 8.5 When Rvalues become Lvalues
8.6 Checking Value Categories with
decltypeto Check the Type of Names
decltypeto Check the Value Category
- 8.6.1 Using
- 8.7 Summary
- 8.1 Value Categories
- 1. The Power of Move Semantics
II Move Semantics in Generic Code
9. Perfect Forwarding
9.1 Motivation for Perfect Forwarding
- 9.1.1 What we Need to Perfectly Forward Arguments
9.2 Implementing Perfect Forwarding
- 9.2.1 Universal (or Forwarding) References
- 9.2.3 The Effect of Perfect Forwarding
9.3 Rvalue References versus Universal References
- 9.3.1 Rvalue References of Actual Types
- 9.3.2 Rvalue References of Function Template Parameters
9.4 Overload Resolution with Universal References
- 9.4.1 Fixing Overload Resolution with Universal References
- 9.5 Perfect Forwarding in Lambdas
- 9.6 Summary
- 9.1 Motivation for Perfect Forwarding
10. Tricky Details of Perfect Forwarding
10.1 Universal References as Non-Forwarding References
10.1.1 Universal References and
- 10.1.2 Universal References in Detail
- 10.1.3 Universal References of Specific Types
- 10.1.1 Universal References and
10.2 Universal or Ordinary Rvalue Reference?
- 10.2.1 Rvalue References of Members of Generic Types
- 10.2.2 Rvalue References of Parameters in Class Templates
- 10.2.3 Rvalue References of Parameters in Full Specializations
10.3 How the Standard Specifies Perfect Forwarding
- 10.3.1 Explicit Specification of Types for Universal References
- 10.3.2 Conflicting Template Parameter Deduction with Universal References
- 10.3.3 Pure RValue References of Generic Types
10.4 Nasty Details of Perfect Forwarding
- 10.4.1 “Universal” versus “Forwarding” Reference
&&for Both Ordinary Rvalues and Universal References?
- 10.5 Summary
- 10.1 Universal References as Non-Forwarding References
11. Perfect Passing with
11.1 Default Perfect Passing
- 11.1.1 Default Perfect Passing in Detail
11.2 Universal References with
11.2.1 Type Deduction of
11.2.2 Perfectly Forwarding an
- 11.2.1 Type Deduction of
auto&&as Non-Forwarding Reference
11.3.1 Universal References and the Range-Based
- 11.3.1 Universal References and the Range-Based
- 11.4 Perfect Forwarding in Lambdas
auto&&in C++20 Function Declarations
- 11.6 Summary
- 11.1 Default Perfect Passing
12. Perfect Returning with
- 12.1 Perfect Returning
12.2.1 Return Type
- 12.2.2 Deferred Perfect Returning
- 12.2.3 Perfect Forwarding and Returning with Lambdas
- 12.2.1 Return Type
- 12.3 Summary
- 9. Perfect Forwarding
III Move Semantics in the C++ Standard Library
13. Move-Only Types
13.1 Declaring and Using Move-Only Types
- 13.1.1 Declaring Move-Only Types
- 13.1.2 Using Move-Only Types
- 13.1.3 Passing Move-Only Objects as Arguments
- 13.1.4 Returning Move-Only Objects by Value
- 13.1.5 Moved-From States of Move-Only Objects
- 13.2 Summary
- 13.1 Declaring and Using Move-Only Types
14. Moving Algorithms and Iterators
- 14.1 Moving Algorithms
- 14.2 Removing Algorithms
14.3 Move Iterators
- 14.3.1 Move Iterators in Algorithms
- 14.3.2 Move Iterators in Constructors and Member Functions
- 14.4 Summary
15. Move Semantics in Types of the C++ Standard Library
15.1 Move Semantics for Strings
- 15.1.1 String Assignments and Capacity
15.2 Move Semantics for Containers
- 15.2.1 Basic Move Support for Containers as a Whole
- 15.2.2 Insert and Emplace Functions
15.2.3 Move Semantics for
15.3 Move Semantics for Vocabulary Types
- 15.3.1 Move Semantics for Pairs
15.3.2 Move Semantics for
15.4 Move Semantics for Smart Pointers
15.4.1 Move Semantics for
15.4.2 Move Semantics for
- 15.4.1 Move Semantics for
15.5 Move Semantics for IOStreams
- 15.5.1 Moving IOStream Objects
- 15.5.2 Using Temporary IOStreams
15.6 Move Semantics for Multithreading
- 15.6.2 Futures, Promises, and Packaged Tasks
- 15.7 Summary
- 15.1 Move Semantics for Strings
- CPP file
- forwarding reference
- full specialization
- header file
- include file
- incomplete type
- named return value optimization (NRVO)
- return value optimization (RVO)
- small/short string optimization (SSO)
- translation unit
- universal reference
- value category
- variadic template
- 13. Move-Only Types
The Leanpub 45-day 100% Happiness Guarantee
Within 45 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.
See full terms
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.
C++ Best PracticesJason Turner
Level up your C++, get the tools working for you, eliminate common problems, and move on to more exciting things!
Functional Design and ArchitectureAlexander Granin
Software Design in Functional Programming, Design Patterns and Practices, Methodologies and Application Architectures. How to build real software in Haskell with less efforts and low risks. The first complete source of knowledge.
OpenIntro StatisticsDavid Diez, Christopher Barr, Mine Cetinkaya-Rundel, and OpenIntro
A 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.
R Programming for Data ScienceRoger D. Peng
This book brings the fundamentals of R programming to you, using the same material developed as part of the industry-leading Johns Hopkins Data Science Specialization. The skills taught in this book will lay the foundation for you to begin your journey learning data science. Printed copies of this book are available through Lulu.
C++20 is the next big C++ standard after C++11. As C++11 did it, C++20 changes the way we program modern C++. This change is, in particular, due to the big four of C++20: ranges, coroutines, concepts, and modules.
I am a Software Engineer and I am in ChargeAlexis Monville and Michael Doyle
I am a Software Engineer and I am in Charge is a real-world, practical book that helps you increase your impact and satisfaction at work no matter who you work with.
In the book, we will follow Sandrine, a fictional character who learns to think in a new way enabling her to take a different course of action.
Invest In Digital Health - The Medical Futurist's GuideDr. Bertalan Mesko
Artificial Intelligence and Digital Health are booming. In this book, we explain why now it's a good time to invest in Digital Health and give recommendations on where to invest by looking at the top 24 technological trends we find the most promising.
Atomic KotlinBruce Eckel and Svetlana Isakova
For both beginning and experienced programmers! From the author of the multi-award-winning Thinking in C++ and Thinking in Java together with a member of the Kotlin language team comes a book that breaks the concepts into small, easy-to-digest "atoms," along with exercises supported by hints and solutions directly inside IntelliJ IDEA!
The Hundred-Page Machine Learning BookAndriy Burkov
Everything you really need to know in Machine Learning in a hundred pages.
Mastering STM32Carmine Noviello
With more than 600 microcontrollers, STM32 is probably the most complete ARM Cortex-M platform on the market. This book aims to be the first guide around that introduces the reader to this exciting MCU portfolio from ST Microelectronics and its official CubeHAL.
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...
The Future of Digital Health
6 BooksWe 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 and how technology giants such as Amazon or Google want to conquer...
Cisco CCNA 200-301 Complet
4 BooksCe lot comprend les quatre volumes du guide préparation à l'examen de certification Cisco CCNA 200-301.
CCDE Practical Studies (All labs)
3 BooksCCDE lab
"The C++ Standard Library" and "Concurrency with Modern C++"
2 BooksGet my books "The C++ Standard Library" and "Concurrency with Modern C++" in a bundle. The first book gives you the details you should know about the C++ standard library; the second one dives deeper into concurrency with modern C++. In sum, you get more than 600 pages full of modern C++ and about 250 source files presenting the standard library...
Modern Management Made Easy
3 BooksRead all three Modern Management Made Easy books. Learn to manage yourself, lead and serve others, and lead the organization.
Programming with Ease
3 BooksAlle drei Bände der Serie Programming with Ease in einem Paket. Darin findest du alles, was ich dir zu den wichtigsten Phasen der Softwareentwicklung im Hinblick auf Clean Code Development für langfristig hohe Produktivität sagen kann.Im Band Slicing findest du die Anforderungsanalyse im Rahmen eines iterativ-inkrementellen Vorgehensmodells aus...
2 BooksUnveil the power of Ansible and Vagrant with this bundle at a special price. You'll have everything you need to get started with Vagrant - learn the basics and how to create your virtual development environments, using Ansible as provisioner! About Vagrant Cookbook Vagrant Cookbook is a complete guide to get started with Vagrant and create your...
2 BooksDocker and Kubernetes are taking the world by storm! These books will get you up-to-speed fast! Docker Deep Dive is over 400 pages long, and covers all objectives on the Docker Certified Associate exam.The Kubernetes Book includes everything you need to get up and running with Kubernetes!
Growing Agile: The Complete Coach's Guide
7 BooksGrowing Agile: Coach's Guide Series This bundle provides a collection of training and workshop plans for a variety of agile topics. The series is aimed at agile coaches, trainers and ScrumMasters who often find themselves needing to help teams understand agile concepts. Each book in the series provides the plans, slides, handouts and activity...