modern-cpp-tutorial-en-us原版完整文件.docx

上传人:暗伤 文档编号:96870203 上传时间:2024-03-27 格式:DOCX 页数:89 大小:885.07KB
返回 下载 相关 举报
modern-cpp-tutorial-en-us原版完整文件.docx_第1页
第1页 / 共89页
modern-cpp-tutorial-en-us原版完整文件.docx_第2页
第2页 / 共89页
点击查看更多>>
资源描述

《modern-cpp-tutorial-en-us原版完整文件.docx》由会员分享,可在线阅读,更多相关《modern-cpp-tutorial-en-us原版完整文件.docx(89页珍藏版)》请在得力文库 - 分享文档赚钱的网站上搜索。

1、Modern C+ Tutorial: C+11/14/17/20 On the FlyChangkun Ou (hiatchangkun.de)Last update: January 24, 2021NoticeThe content in this PDF file may outdated, please check our website or GitHub repository for the latest book updates.LicenseThis work was written by Ou Changkun and licensed under a Creative C

2、ommons Attribution-NonCommercial-NoDerivatives 4.0 International License. http:/creativecommons.org/licenses/by-nc-nd/4.0/2CONTENTSCONTENTSContents7Preface8Introduction8Targets8Purpose9Code9Exercises9Chapter 01: Towards Modern C+91.1 Deprecated Features101.2 Compatibilities with C11Further Readings1

3、3Chapter 02: Language Usability Enhancements132.1 Constants13nullptr13constexpr152.2 Variables and initialization17if-switch17Initializer list18Structured binding202.3 Type inference20auto20decltype22tail type inference23decltype(auto)242.4 Control flow25if constexpr25Range-based for loop252.5 Templ

4、ates26Extern templates26The “”26Type alias templates27Default template parameters28Variadic templates28Fold expression31Non-type template parameter deduction312.6 Object-oriented32Delegate constructor32Inheritance constructor33Explicit virtual function overwrite33override34final34Explicit delete def

5、ault function34Strongly typed enumerations35Conclusion36Exercises36Chapter 03: Language Runtime Enhancements373.1 Lambda Expression37Basics37Generic Lambda393.2 Function Object Wrapper40std:function40std:bind and std:placeholder413.3 rvalue Reference41lvalue, rvalue, prvalue, xvalue42rvalue referenc

6、e and lvalue reference43Move semantics45Perfect forwarding46Conclusion50Further Readings50Chapter 04 Containers504.1 Linear Container50std:array50std:forward_list524.2 Unordered Container524.3 Tuples54Basic Operations54Runtime Indexing55Merge and Iteration56Conclusion56Chapter 05 Smart Pointers and

7、Memory Management575.1 RAII and Reference Counting575.2 std:shared_ptr575.3 std:unique_ptr595.4 std:weak_ptr60Conclusion62Further Readings62Chapter 06 Regular Expression626.1 Introduction62Ordinary characters63Special characters63Quantifiers636.2 std:regex and Its Related64Conclusion66Exercise66Furt

8、her Readings68Chapter 07 Parallelism and Concurrency687.1 Basic of Parallelism687.2 Mutex and Critical Section687.3 Future707.4 Condition Variable717.5 Atomic Operation and Memory Model73Atomic Operation74Concistency Model76Memory Orders78Conclusion81Exercises81Further Readings81Chapter 08 File Syst

9、em818.1 Document and Link818.2 std:filesystem82Further Readings82Chapter 09 Minor Features829.1 New Type82long long int829.2 noexcept and Its Operations829.3 Literal84Raw String Literal84Custom Literal849.4 Memory Alignment85Conclusion86Chapter 10 Outlook: Introduction of C+2086Concept86Module87Cont

10、ract87Range87Coroutine87Conclusion87Further Readings87Appendix 1: Further Study Materials88Appendix 2: Modern C+ Best Practices88Common Tools88Coding Style88Overall Performance88Code Security88Maintainability89Portability89PREFACEPrefaceIntroductionC+ user group is fairly large. From the advent of C

11、+98 to the official finalization of C+11, it has accumulated over a decade. C+14/17 is an important complement and optimization for C+11, and C+20 brings this language to the door of modernization. The extended features of all these new standards are given to the C+ language. Infused with new vitali

12、ty. C+ programmers, who are still using traditional C+ (this book refers to C+98 and its previous C+ standards as traditional C+), may even amazed by the fact that they are not using the same language while reading modern C+ code.Modern C+ (this book refers to C+11/14/17/20) introduces a lot of feat

13、ures into traditional C+, which makes the whole C+ become language that modernized. Modern C+ not only enhances the usability of the C+ language itself, but the modification of the auto keyword semantics gives us more confidence in manipulating extremely complex template types. At the same time, a l

14、ot of enhancements have been made to the language runtime. The emergence of Lambda expressions has made C+ have the “closure” feature of “anonymous functions”, which is almost in modern programming languages (such as Python/Swift/. It has become commonplace, and the emergence of rvalue references ha

15、s solved the problem of temporary object efficiency that C+ has long been criticized.C+17 is the direction that has been promoted by the C+ community in the past three years. It also points out an important development direction of modern C+ programming. Although it does not appear as much as C+11,

16、it contains a large number of small and beautiful languages and features (such as structured binding), and the appearance of these features once again corrects our programming paradigm in C+.Modern C+ also adds a lot of tools and methods to its own standard library, such as std:thread at the level o

17、f the language itself, which supports concurrent programming and no longer depends on the underlying system on different platforms. The API implements cross-platform support at the language level; std:regex provides full regular expression support and more. C+98 has been proven to be a very successf

18、ul “paradigm”, and the emergence of modern C+ further promotes this paradigm, making C+ a better language for system programming and library development. Concepts provide verification on the compile-time of template parameters, further enhancing the usability of the language.In conclusion, as an adv

19、ocate and practitioner of C+, we always maintain an open mind to accept new things, and we can promote the development of C+ faster, making this old and novel language more vibrant.Targets This book assumes that readers are already familiar with traditional C+ (i.e. C+98 or earlier), at least they d

20、o not have any difficulty in reading traditional C+ code. In other words, those who have long experience in traditional C+ and people who desire to quickly understand the features8PurposeCHAPTER 01: TOWARDS MODERN C+of modern C+ in a short period of time are well suited to read the book; This book i

21、ntroduces to a certain extent of the dark magic of modern C+. However, these magics are very limited, they are not suitable for readers who want to learn advanced C+. The purpose of this book is offering a quick start for modern C+. Of course, advanced readers can also use this book to review and ex

22、amine themselves on modern C+.PurposeThe book claims “On the Fly”. Its intent is to provide a comprehensive introduction to the relevant features regarding modern C+ (before 2020s). Readers can choose interesting content according to the following table of content to learn and quickly familiarize th

23、e new features you would like to learn. Readers should aware that all of these features are not required. It should be learnt when you really need it.At the same time, instead of grammar-only, the book introduces the historical background as simple as possible of its technical requirements, which pr

24、ovides great help in understanding why these features comes out.In addition, The author would like to encourage that readers should be able to use modern C+ directly in their new projects and migrate their old projects to modern C+ gradually after read the book.CodeEach chapter of this book has a lo

25、t of code. If you encounter problems when writing your own code with the introductory features of the book, you might as well read the source code attached to the book. You can find the book here. All the code organized by chapter, the folder name is the chapter number.ExercisesThere are few exercis

26、es At the end of each chapter of the book. It is for testing whether you can use the knowledge points in the current chapter. You can find the possible answer to the problem from here. The folder name is the chapter number.Chapter 01: Towards Modern C+Compilation Environment: This book will use clan

27、g+ as the only compiler used, and always use the -std=c+2a compilation flag in your code. clang+ -vApple LLVM version 10.0.1 (clang-1001.0.46.4)91.1 Deprecated FeaturesCHAPTER 01: TOWARDS MODERN C+Target: x86_64-apple-darwin18.6.0 Thread model: posixInstalledDir: /Library/Developer/CommandLineTools/

28、usr/bin1.1 Deprecated FeaturesBefore learning modern C+, lets take a look at the main features that have been deprecated since C+11:Note: Deprecation is not completely unusable, it is only intended to imply that features will disappear from future standards and should be avoided. However, the deprec

29、ated features are still part of the standard library, and most of the features are actually “permanently” reserved for compatibility reasons. The string literal constant is no longer allowed to be assigned to a char *. If you need to assign and initialize a char * with a string literal constant, you

30、 should use const char * or auto.char *str = hello world!; / A deprecation warning will appear C+98 exception description, unexpected_handler, set_unexpected() and other related features are deprecated and should use noexcept. auto_ptr is deprecated and unique_ptr should be used. register keyword is

31、 deprecated and can be used but no longer has any practical meaning. The + operation of the bool type is deprecated. If a class has a destructor, the properties for which it generates copy constructors and copy assignment operators are deprecated. C language style type conversion is deprecated (ie u

32、sing (convert_type) before vari- ables, and static_cast, reinterpret_cast, const_cast should be used for type conver- sion. In particular, some of the C standard libraries that can be used are deprecated in the latest C+17 standard, such as , , and Wait and many moreThere are also other features suc

33、h as parameter binding (C+11 provides std:bind and std:function), export, and etc. are also deprecated. These features mentioned above If you have never used or heard of it, please dont try to understand them. You should move closer to the new standard and learn new features directly. After all, tec

34、hnology is moving forward.101.2 Compatibilities with CCHAPTER 01: TOWARDS MODERN C+Figure 1: Figure 1.2: Compatabilities between ISO C and ISO C+1.2 Compatibilities with CFor some force majeure and historical reasons, we had to use some C code (even old C code) in C+, for example, Linux system calls

35、. Before the advent of modern C+, most people talked about “what is the difference between C and C+”. Generally speaking, in addition to answering the object-oriented class features and the template features of generic programming, there is no other opinion, or even a direct answer. “Almost” is also

36、 a lot of people. The Venn diagram in Figure 1.2 roughly answers the C and C+ related compatibility.From now on, you should have the idea that “C+ is not a superset of C” in your mind (and not from the beginning, later References for further reading (# further reading references) The difference betw

37、een C+98 and C99 is given). When writing C+, you should also avoid using program styles such as void* whenever possible. When you have to use C, you should pay attention to the use of extern C, separate the C language code from the C+ code, and then unify the link, for instance:/ foo.h#ifdef cpluspl

38、usextern C #endifint add(int x, int y);#ifdef cplusplus12#endif/ foo.cint add(int x, int y) return x+y;/ 1.1.cpp#include foo.h #include #include int main() out = std:ref(std:cout Result from C code: add(1, 2)() out.get() .n;();return 0;You should first compile the C code with gcc: gcc -c foo.cCompil

39、e and output the foo.o file, and link the C+ code to the .o file using clang+ (or both compile to .o and then link them together):clang+ 1.1.cpp foo.o -std=c+2a -o 1.1Of course, you can use Makefile to compile the above code:C = gccCXX = clang+SOURCE_C = foo.c OBJECTS_C = foo.oSOURCE_CXX = 1.1.cpp T

40、ARGET = 1.1LDFLAGS_COMMON = -std=c+2aFurther ReadingsCHAPTER 02: LANGUAGE USABILITY ENHANCEMENTSall:$(C) -c $(SOURCE_C)$(CXX) $(SOURCE_CXX) $(OBJECTS_C) $(LDFLAGS_COMMON) -o $(TARGET)clean:rm -rf *.o $(TARGET)Note: Indentation in Makefile is a tab instead of a space character. If you copy this code

41、di- rectly into your editor, the tab may be automatically replaced. Please ensure the indentation in the Makefile. It is done by tabs.If you dont know the use of Makefile, it doesnt matter. In this tutorial, you wont build code that is written too complicated. You can also read this book by simply u

42、sing clang+-std=c+2a on the command line.If you are new to modern C+, you probably still dont understand the following small piece of code above, namely:out = std:ref(std:cout Result from C code: add(1, 2)() out.get() .n;();Dont worry at the moment, we will come to meet them in our later chapters.Fu

43、rther Readings A Tour of C+ (2nd Edition) Bjarne Stroustrup History of C+ C+ compiler support Incompatibilities Between ISO C and ISO C+Chapter 02: Language Usability EnhancementsWhen we declare, define a variable or constant, and control the flow of code, object-oriented functions, template program

44、ming, etc., before the runtime, it may happen when writing code or compiler compiling code. To this end, we usually talk about language usability, which refers to the language behavior that occurred before the runtime.2.1 ConstantsnullptrThe purpose of nullptr appears to replace NULL. In a sense, tr

45、aditional C+ treats NULL and 0as the same thing, depending on how the compiler defines NULL, and some compilers define NULL as132.1 ConstantsCHAPTER 02: LANGUAGE USABILITY ENHANCEMENTS(void*)0) Some will define it directly as 0.C+ does not allow to implicitly convert void * to other types. But if th

46、e compiler tries to define NULL as (void*)0), then in the following code:char *ch = NULL;C+ without the void * implicit conversion has to define NULL as 0. This still creates a new problem. Defining NULL to 0 will cause the overloading feature in C+ to be confusing. Consider the following two foo functions:void foo(char*); void foo(int);Then the foo(NULL); statement will call foo(int), which will cause the code to be counterintuitive.To solve t

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 技术资料 > 技术方案

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知得利文库网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号-8 |  经营许可证:黑B2-20190332号 |   黑公网安备:91230400333293403D

© 2020-2023 www.deliwenku.com 得利文库. All Rights Reserved 黑龙江转换宝科技有限公司 

黑龙江省互联网违法和不良信息举报
举报电话:0468-3380021 邮箱:hgswwxb@163.com