C++ Initialization Story A Guide Through All Initialization Options and Related C++ Areas Bartłomiej Filipek Thisbookisforsaleathttp://leanpub.com/cppinitbook Thisversionwaspublishedon2022-12-23 ThisisaLeanpubbook.LeanpubempowersauthorsandpublisherswiththeLean Publishingprocess.LeanPublishingistheactofpublishinganin-progressebookusing lightweighttoolsandmanyiterationstogetreaderfeedback,pivotuntilyouhavetheright bookandbuildtractiononceyoudo. ©2021-2022BartłomiejFilipek Contents AbouttheBook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i Whyshouldyoureadthisbook? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i Learningobjectives. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i Thestructureofthebook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii Whoisthisbookfor? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii Prerequisites. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii Readerfeedback&errata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii Examplecode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iv Codelicense . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iv Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iv Specialsections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vi AbouttheAuthor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . viii RevisionHistory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix 1. LocalVariablesandSimpleTypes . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Startingwithsimpletypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Settingvaluestozero . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Initializationwithaggregates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Defaultdatamemberinitialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2. InitializationWithConstructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Asimpleclasstype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Basicsofconstructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Bodyofaconstructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 AddingconstructorstoDataPacket . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 CONTENTS Compiler-generateddefaultconstructors . . . . . . . . . . . . . . . . . . . . . . . . 26 Explicitconstructorsandconversions . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Differencebetweendirectandcopyinitialization . . . . . . . . . . . . . . . . . . . 32 Implicitconversionandconvertingconstructors . . . . . . . . . . . . . . . . . . . . 34 Constructorsummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 3. CopyandMoveOperations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 Copyconstructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 Moveconstructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 Distinguishingfromassignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 Addingdebugloggingtoconstructors . . . . . . . . . . . . . . . . . . . . . . . . . . 57 Trivialclassesanduser-provideddefaultconstructors . . . . . . . . . . . . . . . . . 59 4. DelegatingandInheritingConstructors . . . . . . . . . . . . . . . . . . . . . . . 64 Delegatingconstructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 Inheritingconstructors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 5. Destructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 Objectsallocatedontheheap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 Destructorsanddatamembers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 Virtualdestructorsandpolymorphism. . . . . . . . . . . . . . . . . . . . . . . . . . 80 Partiallycreatedobjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Acompiler-generateddestructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 Summaryandusecases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 6. TypeDeductionandInitialization . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 Deductionwithauto. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 Rulesforautotypededuction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 Deductionwithdecltype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 Printingtypeinfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 StructuredbindingsinC++17 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 Lifetimeextension,references,andloops . . . . . . . . . . . . . . . . . . . . . . . . 103 AlmostAlwaysAuto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 7. QuizfromChapters1…6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 CONTENTS 8. Non-StaticDataMemberInitialization . . . . . . . . . . . . . . . . . . . . . . . . 112 Howitworks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 Investigation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 Experiments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 OtherformsofNSDMI. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 CopyconstructorandNSDMI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 MoveconstructorandNSDMI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 C++14changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 C++20changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 LimitationsofNSDMI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 NSDMI:AdvantagesandDisadvantages. . . . . . . . . . . . . . . . . . . . . . . . . 129 NSDMIsummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 9. ContainersasDataMembers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 Thebasics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 Usingstd::initializerlist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 Exampleimplementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 Thecostofcopyingelements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 Someinconvenience-non-copyabletypes . . . . . . . . . . . . . . . . . . . . . . . 146 Moreoptions(advanced) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 10. Non-regularDataMembers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 Constantnon-staticdatamembers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 Pointersasdatamembers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 Smartpointersasdatamembers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 Referencesasdatamembers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 11. Non-localobjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 Storagedurationandlinkage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 Initializationofnon-localstaticobjects . . . . . . . . . . . . . . . . . . . . . . . . . 180 constinitinC++20 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 Staticvariablesinafunctionscope . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 Aboutstaticdatamembers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 Motivationforinlinevariables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 Globalinlinevariables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 constexprandinlinevariables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 CONTENTS 12. AggregatesandDesignatedInitializersinC++20 . . . . . . . . . . . . . . . . . . 199 AggregatesinC++20 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 ThebasicsofDesignatedInitializers . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 Advantagesofdesignatedinitialization . . . . . . . . . . . . . . . . . . . . . . . . . 204 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 13. TechniquesandUseCases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 Usingexplicitforstrongtypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 Bestwaytoinitializestringdatamembers . . . . . . . . . . . . . . . . . . . . . . 212 Reducingextracopiesthroughemplaceandin_place . . . . . . . . . . . . . . . . 215 Thecopyandswapidiom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 CRTPclasscounter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 Severalinitializationtypesinoneclass . . . . . . . . . . . . . . . . . . . . . . . . . 226 Meyer’sSingletonandC++11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 Factorywithself-registeringtypesandstaticinitialization . . . . . . . . . . . . . . 231 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 14. TheFinalQuizAndExercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 AppendixA-RulesforSpecialMemberFunctionGeneration . . . . . . . . . . . . 248 Thediagram. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248 Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 AppendixB-QuizandExercisesAnswers . . . . . . . . . . . . . . . . . . . . . . . . 254 Thequizfromchapters1…6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 Thefinalquiz . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 Solutiontothefirstcodingproblem,NSDMI . . . . . . . . . . . . . . . . . . . . . . 255 Solutiontothesecondcodingproblem,NSDMI . . . . . . . . . . . . . . . . . . . . 255 Solutiontothethirdcodingproblem,inline . . . . . . . . . . . . . . . . . . . . . 257 Solutiontothefourthcodingproblem,fixcode . . . . . . . . . . . . . . . . . . . . 257 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 About the Book Initialization in C++ is a hot topic! The internet is full of discussions about best practices, andthereareevenfunnymemesonthatsubject.Thesituationisnotsurprising,asthereare morethanadozenwaystoinitializeasimpleintegervalue,complexrulesfortheauto-type deduction,datamembers,andobjectlifetimenuances. Andherecomesthebook. Throughout this text, you will learn practical options to initialize various categories of variables and data members in Modern C++. More specifically, this text teaches multiple types of initialization, constructors, non-static data member initialization, inline variables, designated initializers, and more. Additionally, you’ll see the changes and new techniques fromC++11toC++20andlotsofexamplestoroundoutyourunderstanding. The plan is to explain most (if not all) parts of initialization, learn lots of excellent C++ techniques,andseewhathappensunderthehood. Why should you read this book? With Modern C++ (since C++11), we have many new features to streamline work and simplify our code. One area of improvement is the initialization. Modern C++ added new initialization rules, trying to make it easy while keeping old behavior and compatibility (mainly from the C language). Sometimes the rules might seem confusing and complex, though,andeventheISOcommitteemightneedtocorrectsomethingsalongtheway.The bookwillhelpyounavigatethroughthoseprinciplesandunderstandthistopicbetter.What’s more,initializationisjustoneaspectofthistext.You’lllearnallrelatedtopicsaroundclasses, constructors,destructors,objectlifetime,orevenhowthecompilerprocessesdataatstart-up. Learning objectives Thegoalistoequipyouwiththefollowingknowledge: • Explain rules about object initialization, including regular variables, data members, andnon-localobjects. i AbouttheBook ii • How to implement special member functions (constructors, destructors, copy/move operations)andwhentheyarehelpful. • How to efficiently initialize non-static data members using C++11 features like non- staticdatamemberinitialization,inheriting,anddelegatingconstructors. • Howtostreamlineworkingwithstaticvariablesandstaticdatamemberswithinline variablesfromC++17. • How to work with container-like members, non-copyable data members (like const datamembers)ormove-ableonlydatamembers,orevenlambdas. • Whatisanaggregate,andhowtocreatesuchobjectswithdesignatedinitializersfrom C++20. The structure of the book Thebookcontains14chaptersinthefollowingstructure: • Chapters 1 to 5 create a foundation for the rest of the book. They cover basic initializationrules,constructors,destructors,andthebasicsofdatamembers. • Chapter6isashortquizonconstructors.Youcancheckyourknowledgefromthefirst “part”ofthebook. • Chapter7(inprogress):Typededuction. • Chapter 8 describes Non-static Data Member Initialization (NSDMI), a powerful feature from C++11 that improves how we work with data members. At the end of thechapter,youcansolveafewexercises. • Chapter9discusseshowtoinitializecontainer-likedatamembers. • Chapter10containsinformationaboutnon-regulardatamembersandhowtohandle theminaclass.You’lllearnaboutconstdatamembers,unique_ptrasadatamember, andreferences. • Chapter11describesstaticnon-localvariables,staticobjects,variousstorageduration options,andinlinevariablesfromC++17andconstinitfromC++20. • Chapter 12 moves to C++20 and describes Designated Initializers, a handy feature basedonsimilarthingfromtheClanguage. • Chapter 13 shows various techniques like passing strings into constructors, strong typing,CRTPclasscounter,Copyandswapidiom,andmore. • Chapter14isthefinalquizwithquestionsfromthewholebook. AbouttheBook iii Andtherearetwoappendices: • Appendix A - a handy guide about rules for compiler-generated special member functions. • AppendixB-answerstoquizzesandexercises. Who is this book for? Thebookisintendedforbeginner/intermediateC++programmerswhowanttolearnvarious aspectsofinitializationinModernC++(fromC++11toC++20). Youshouldknowatleastsomeofthebasicsofcreatingandusingcustomclasses. This text is also helpful for experienced programmers who know older C++ standards and wanttomoveintoC++17/C++20. Prerequisites • YoushouldhavebasicknowledgeofC++expressionsandprimitivetypes. • Youshouldbeabletoimplementanelementaryclasswithseveraldatamembers.Know howtocreateandmanipulateobjectsofsuchaclassinabasicway. Reader feedback & errata Ifyouspotanerror,atypo,agrammarmistake,oranythingelse(especiallylogicalissues!) thatshouldbecorrected,[email protected]. Here’stheerratawiththelistoffixes: https://www.cppstories.com/p/cppinitbook/ Yourfeedbackmatters!Writinganhonestreviewcanhelpwiththebookpromotionandthe qualityofmyfurtherwork. What’smore,thebookhasadedicatedpageatGoodReads.Pleaseshareyourfeedbackat: C++InitializationStorybyBartłomiejFilipek¹. ¹https://www.goodreads.com/book/show/62606823-c-initialization-story