Effective Modern C++完整版

所需积分/C币:44 2014-11-22 09:28:45 5.74MB PDF

新版本的Effective C++ 内容为C++11 C++14全部重写
1 Item 17: Consider pass by value for cheap-to-move parameters that are always copied 120 Item 18: Consider emplacement instead of insertion 128 4 Item 19: Understand special member function generation. 136 Chapter 4 Smart Pointers 145 5678 Item 20: Use std: unique_ptr for exclusive-ownership resource management. 147 8 Item 21: Use std: shared_ptr for shared-ownership resource management 154 Item 22: Use std: weak_ptr for std: shared_-ptr-like pointers that can 11 angle 164 12 Item 23: Prefer std: make unique and std: make shared to direct use of new 170 14 Item 24: When using the Pimpl Idiom, define special member functions in the implementation file 179 Chapter 5 Rvalue References, Move Semantics, and Perfect Forwarding 189 17 Item 25: Understand std:: move and std:: forward 190 18 Item 26: Distinguish universal references from rvalue references 197 Item 27: Use std: move on rvalue references std: forward on universal references 202 21 Item 28: Avoid overloading on universal references 210 22 Item 29: Familiarize yourself with alternatives to overloading on universal 23 references 217 24 Item 30: Understand reference collapsing 228 Page 2 1 Item 31: Assume that move operations are not present, not cheap, and not used 234 Item 32: Familiarize yourself with perfect forwarding failure cases 238 4 Chapter 6 Lambda expressions 249 Item 33: Avoid default capture modes 251 567 Item 34: Use init capture to move objects into closures 258 Item 35: Use decltype on auto&& parameters to std: forward them. 264 8 Item 36: Prefer lambdas to std:: bind 267 9 Chapter 7 The Concurrency API 275 10 Item 37: Prefer task-based programming to thread- based 275 11 Item 38: Specify std: launch: async if asynchronicity is essential. 280 12 Item 39: Make std: threads unjoinable on all paths 286 Item 40: Be aware of varying thread handle destructor behavior. 293 1 4 Item 41: Consider yoid futures for one-shot event communication 299 15 Item 42: Use std: atomic for concurrency, volatile for special memory 308 Page 3 1 Introduction 2 If you're an experienced C++ programmer and are anything like me, you initiall 3 approached C++1l thinking, Yes, yes, i get it. It's C++, only more so. But as your 4 knowledge of the revised language increased, you were surprised by the scale of the changes. auto objects, range-based for loops, lambda expressions, and rvalue 6 references change the very face of C ++, to say nothing of the new concurrency fea 7 tures And then there are the idiomatic changes! 0 and typedefs are out, nullptr 8 and alias declarations are in. Enums should now be scoped. Smart pointers are now preferable to built-in ones. Moving objects is normally better than copying 10 them There's a lot to learn about c++11 11 The adoption of C++ 14 hardly made things easier. 12 So.a lot to learn. More importantly, a lot to learn about making effective use of the 3 new capabilities. If you need information on the basic syntax or semantics of fed 14 tures in"modern"C++, resources abound, but if you're looking for guidance on 15 how to employ the features to create software thats correct, efficient, maintaina 16 ble, and portable, the search is more challenging. That's where this book comes in 17 It's devoted not to describing the features of C++11 and C++14, but rather to their 18 effective application 19 The information in the book is broken into guidelines called Items. Want to under 20 stand the various forms of type deduction? Or to know when (and when not] to 21 declare objects using auto? Are you interested in why const member functions 22 should be thread-safe, how to implement the Pimpl Idiom using 23 std: unique_ptr, why you should avoid default capture modes in lambda ex 24 pressions, or the differences between (and proper uses of) std: atomic and 25 volatile? The answers are all here. Furthermore, theyre platform-independent, 26 Standards-conformant answers This is a book about portable C++. 27 Items comprise guidelines, not rules, because guidelines have exceptions. The 28 most important part of each Item is not the advice it offers, but the rationale be 29 hind the advice. Once you've read that, you'll be in a position to determine whether the circumstances of your project justify disregarding the Items guidance. The Page 4 1 true goal of this book isnt to tell you what to do or what to avoid doing but to 2 convey a deeper understanding of how things work in C++11 and C++14 3 Terminology and Conventions 4 To make sure we understand one another, it's important to agree on some termi 5 nology, beginning, ironically, with" C++. There have been four standardized ver- 6 sions of C++, each named after the year in which the corresponding Iso Standard was adopted: C++98, C++03, C++1l, and C++14. C++98 and C++03 differ only in 8 subtle technical details, so in this book, i refer to both as c++98 9 When I mention C++98, I mean only that version of the language Where i refer to 10 C++11, I mean both C++11 and C++14, because C++14 is effectively a superset of 11 C++11. When I write C++14, I mean specifically C++14. And if i simply mention 12 C++, I'm making a broad statement that pertains to all language versions. As a re 3 sult, I might say that C++ places a premium on efficiency (true for all versions), 14 that C++98 lacks support for concurrency (true for C++98 only), that C++11 sup 15 ports lambda expressions (true for C++11 and C++14), and that C++14 offers gen- 16 eralized function return type deduction(true for C++14 only) 17 C++11's most pervasive feature is probably move semantics, and the foundation of 18 move semantics is distinguishing expressions that are rvalues from those that are 19 values. That's because rvalues indicate objects eligible for move operations, while 20 lvalues generally dont In concept (though not always in practice), rvalues corre 21 spond to anonymous temporary objects returned from functions, while lvalues 22 correspond to objects you can refer to, either by name or by following a pointer or 23 reference 24 A useful heuristic to determine whether an expression is an lvalue is to ask if you 25 can take its address. If you can, it typically is. If you cant, it's usually an rvalue. A 26 nice feature of this heuristic is that it helps you remember that the type of an ex 27 pression is independent of whether the expression is an lvalue or an rvalue. That 28 is, given a type t, you can have both lvalues of type T and rvalues of type T It's es 29 pecially important to remember this when dealing with a parameter of rvalue ref- 30 erence type, because the parameter itself is an lvalue: ge 1 class widget t 2 public 3 Widget (Widget&& rhs); //rhs is an Lvalue, though it has 4 / an rvalue reference type 6 Here, it'd be perfectly valid to take rhss address inside widget's move construc 7 tor, so rhs is an lvalue, even though its type is an rvalue reference. By similar rea- 8 soning, all parameters are lvalues. 9 This code example demonstrates several conventions I typically follow 10. The class name is Widget. I use widget whenever i want to refer to an arbi- 11 trary user-defined type. Unless i need to show specific details of the class, I use 12 Widget without declaring it 13 I use the parameter name rhs, which stands for"right-hand side. It's my pre 14 ferred parameter name for the move operations (i.e, move constructor and move assignment operator) and the copy operations (i. e, copy constructor and 16 copy assignment operator), though I also employ it for the right-hand parame ter of binary operators: Matrix operator+(const Matrix& lhs, const Matrix& rhs); 19 It's no surprise, I hope, that lhs stands for left-hand side 20 I highlight parts of code or parts of comments to draw your attention to them 21 In the code above, I've highlighted the declaration of rhs and the part of the 22 comment noting that rhs is an lvalue I use". to indicate "other code could go here. This narrow ellipses is differ 24 ent from the wide ellipsis c..) that's used in the source code for C++11s 25 variadic templates. That sounds confusing, but it's not. For example 6 template<typename.. Ts> // these are C++ 27 void processvals(const Ts&... params)// source code 28 // ellipses 29 // this means"some // code goes here 31 Page 6 The declaration of processvals shows that I use typename when declaring type parameters in templates, but that's merely a personal preference; the keyword class would work just as well. On those few occasions where I show 4 code excerpts from a C++ Standard, I declare type parameters using class, be cause that's what the standards do 6 When an object is initialized with another object of the same type, the new object is said to be a copy of the initializing object, even if the copy was created via the 8 move constructor. Regrettably, there's no terminology in C++ that distinguishes 9 between an object that's a copy-constructed copy and one thats a move 10 constructed copy: 11 void some Func(Widget w); someFunc s parameter w // is passed by value 14 Widget wid; // wid is some Widget 15 some Func(wid) // in this call to someFunc 16 //w is a copy of wid thats // created via copy construction 18 some Func(std: move(wid)); // in this call to Some Func, 19 //w is a copy of wid thats created via move construction 21 Copies of rvalues are generally move-constructed, while copies of lvalues are typi 22 cally copy-constructed. An implication is that if you know only that an object is a 23 copy of another object, it's not possible to say how expensive it was to construct 24 the copy. In the code above, for example, there's no way to say how expensive it is 25 to create the parameter w without knowing whether rvalues or lvalues are passed 26 to some Func. You' d also have to know the cost of moving and copying widgets. 27 In a function call, the expressions passed at the call site are the functions argu 28 ments. The arguments are used to initialize the functions parameters In the first 29 call to some Func above the argument is wid. In the second call, the argument is 30 std: move(wid). In both calls, the parameter is W. The distinction between argu- 31 ments and parameters is important, because parameters are lvalues, but the ar- 32 guments with which they are initialized may be rvalues or lvalues. This is especial- ly relevant during the process of perfect forwarding, whereby an argument passed Page 7 1 to a function is passed to a second function such that the original argument 's rval 2 ueness or lvalueness is preserved. ( Perfect forwarding is discussed in more detail 3 in item 32 4 Well-designed functions are exception-safe, meaning they offer at least the basic 5 exception safely guarantee ( i. e, the basic guarantee). Such functions assure callers 6 that even if an exception is emitted, program invariants remain intact (i.e, no data structures are corrupted) and no resources are leaked. Functions offering the 8 strong exception safety guarantee ( i. e, the strong guarantee) assure callers that if 9 an exception is emitted, the state of the program remains as it was prior to the call 0 As Item 16 explains, C++98 Standard Library functions offering the strong guaran 11 tee constrain the applicability of move semantics in the C++11 Standard library 12 I use the term callable entity to refer to anything that can be called using the syntax 13 of a call to a non-member function, i.e., the syntax functionName (arguments) 14 Functions, function pointers, and function objects are all callable entities. Function 15 objects created through lambda expressions are known as closures. It's seldom 16 necessary to distinguish between lambda expressions and the closures they create, 17 so i often refer to both as lambdas .8 In the same vein, I rarely distinguish between function templates (i. e, templates 9 that generate functions ) and template functions (i. e, the functions generated from 20 function templates) Ditto for class templates and template classes 21 Many things in C++ can be both declared and defined. Declarations introduce 22 names without giving details, such as where storage is lo cated or how the entity is 23 implemented 24 extern int x; // object declaration 25 class widget; // class declaration 26 int func(const Widget& w); // function declaration 27 enum class color // scoped enum declaration 28 /(see Item 10) 29 Definitions provide the storage location or implementation details: 30 int x; // object definition Page 8 1 class widget t // class definition 3} 4 int func(const Widget& w) I return W size(;] // function definition 6 enum class color 7 Yellow, Red, blue // scoped enum definition 8 a definition also qualifies as a declaration, so unless it's really important that 9 something is a definition i tend to refer to declarations 10 New C++ Standards generally preserve the validity of code written under older 11 ones, but occasionally the Standardization Committee deprecates features. Thats a 12 warning that the features may be removed from future Standards. You should 13 avoid deprecated features. CThe reason for deprecation is usually that newer fea 14 tures offer the same functionality, but with fewer restrictions or drawbacks 15 std: auto_ ptr is deprecated in C++11, for example, because std: unique ptr 16 does the same job, only better.) 17 Sometimes the Standard says that the result of an operation is undefined behavior. 18 That means that runtime behavior is unpredictable, and it should go without say- 19 ing that you want to steer clear of such uncertainty. Examples of actions with un- o defined behavior include using square brackets(l)to index beyond the bounds 21 of a std: vector, dereferencing an uninitialized iterator, or engaging in a data 22 race (i.e, having two or more threads, at least one of which is a writer, simultane 23 ously access the same memory location) 24 In source code comments i sometimes abbreviate "constructor"as ctor and de 25 structoras dtor 26 Reporting Bugs and Suggesting Improvements 27 Ive done my best to fill this book with clear, accurate, useful information, but sure 28 ly there are ways to make it better. If you find errors of any kind(technical, exposi- 29 tory, grammatical, typographical, etc. or if you have suggestions for how the book 30 could otherwise be improved, please email me at emc++aristeia. com. New ge

...展开详情

评论 下载该资源后可以进行评论 32

fengbingchun 是英文版的
2019-11-10
回复
帝都小茂茂 非常好,多谢
2019-01-29
回复
David_Lee123 很不错,很好的学习资料
2019-01-14
回复
DJWL_COMMON 非常不错,也很清晰
2018-11-13
回复
whc10002 值得学习借鉴
2018-09-30
回复
img
Cu2S

关注 私信 TA的资源

上传资源赚积分,得勋章
最新资源