B. Stroustrup - The C++ Programming Language (794319), страница 9
Текст из файла (страница 9)
My opinion on howto teach C++ to novices is represented by [Stroustrup,2008].There are several independently developed implementations of C++. They are supported by awealth of tools, libraries, and software development environments. To help master all of this youcan find textbooks, manuals, and a bewildering variety of online resources. If you plan to use C++seriously, I strongly suggest that you obtain access to several such sources.
Each has its ownemphasis and bias, so use at least two.1.3.1 Programming in C++The question ‘‘How does one write good programs in C++?’’ is very similar to the question ‘‘Howdoes one write good English prose?’’ There are two answers: ‘‘Know what you want to say’’ and‘‘Practice. Imitate good writing.’’ Both appear to be as appropriate for C++ as they are for English– and as hard to follow.The main ideal for C++ programming – as for programming in most higher-level languages – isto express concepts (ideas, notions, etc.) from a design directly in code. We try to ensure that theconcepts we talk about, represent with boxes and arrows on our whiteboard, and find in our (nonprogramming) textbooks have direct and obvious counterparts in our programs:[1] Represent ideas directly in code.[2] Represent relationships among ideas directly in code (e.g., hierarchical, parametric, andownership relationships).[3] Represent independent ideas independently in code.[4] Keep simple things simple (without making complex things impossible).Section 1.3.1Programming in C++19More specifically:[5] Prefer statically type-checked solutions (when applicable).[6] Keep information local (e.g., avoid global variables, minimize the use of pointers).[7] Don’t overabstract (i.e., don’t generalize, introduce class hierarchies, or parameterizebeyond obvious needs and experience).More specific suggestions are listed in §1.3.2.1.3.2 Suggestions for C++ ProgrammersBy now, many people have been using C++ for a decade or two.
Many more are using C++ in asingle environment and have learned to live with the restrictions imposed by early compilers andfirst-generation libraries. Often, what an experienced C++ programmer has failed to notice over theyears is not the introduction of new features as such, but rather the changes in relationshipsbetween features that make fundamental new programming techniques feasible. In other words,what you didn’t think of when first learning C++ or found impractical just might be a superiorapproach today.
You find out only by reexamining the basics.Read through the chapters in order. If you already know the contents of a chapter, you can bedone in minutes. If you don’t already know the contents, you’ll have learned something unexpected. I learned a fair bit writing this book, and I suspect that hardly any C++ programmer knowsevery feature and technique presented. Furthermore, to use the language well, you need a perspective that brings order to the set of features and techniques.
Through its organization and examples,this book offers such a perspective.Take the opportunity offered by the new C++11 facilities to modernize your design and programming techniques:[1] Use constructors to establish invariants (§2.4.3.2, §13.4, §17.2.1).[2] Use constructor/destructor pairs to simplify resource management (RAII; §5.2, §13.3).[3] Avoid ‘‘naked’’ new and delete (§3.2.1.2, §11.2.1).[4] Use containers and algorithms rather than built-in arrays and ad hoc code (§4.4, §4.5,§7.4, Chapter 32).[5] Prefer standard-library facilities to locally developed code (§1.2.4).[6] Use exceptions, rather than error codes, to report errors that cannot be handled locally(§2.4.3, §13.1).[7] Use move semantics to avoid copying large objects (§3.3.2, §17.5.2).[8] Use unique_ptr to reference objects of polymorphic type (§5.2.1).[9] Use shared_ptr to reference shared objects, that is, objects without a single owner that isresponsible for their destruction (§5.2.1).[10] Use templates to maintain static type safety (eliminate casts) and avoid unnecessary useof class hierarchies (§27.2).It might also be a good idea to review the advice for C and Java programmers (§1.3.3, §1.3.4).1.3.3 Suggestions for C ProgrammersThe better one knows C, the harder it seems to be to avoid writing C++ in C style, thereby losingmany of the potential benefits of C++.
Please take a look at Chapter 44, which describes the differences between C and C++.20Notes to the ReaderChapter 1[1]Don’t think of C++ as C with a few features added. C++ can be used that way, but onlysuboptimally. To get really major advantages from C++ as compared to C, you need toapply different design and implementation styles.[2] Don’t write C in C++; that is often seriously suboptimal for both maintenance and performance.[3] Use the C++ standard library as a teacher of new techniques and programming styles.Note the difference from the C standard library (e.g., = rather than strcpy() for copyingand == rather than strcmp() for comparing).[4] Macro substitution is almost never necessary in C++.
Use const (§7.5), constexpr (§2.2.3,§10.4), enum or enum class (§8.4) to define manifest constants, inline (§12.1.5) to avoidfunction-calling overhead, templates (§3.4, Chapter 23) to specify families of functionsand types, and namespaces (§2.4.2, §14.3.1) to avoid name clashes.[5] Don’t declare a variable before you need it, and initialize it immediately. A declarationcan occur anywhere a statement can (§9.3), in for-statement initializers (§9.5), and in conditions (§9.4.3).[6] Don’t use malloc(). The new operator (§11.2) does the same job better, and instead ofrealloc(), try a vector (§3.4.2).
Don’t just replace malloc() and free() with ‘‘naked’’ new anddelete (§3.2.1.2, §11.2.1).[7] Avoid void∗, unions, and casts, except deep within the implementation of some functionor class. Their use limits the support you can get from the type system and can harm performance. In most cases, a cast is an indication of a design error. If you must use anexplicit type conversion, try using one of the named casts (e.g., static_cast; §11.5.2) for amore precise statement of what you are trying to do.[8] Minimize the use of arrays and C-style strings.
C++ standard-library strings (§4.2), arrays(§8.2.4), and vectors (§4.4.1) can often be used to write simpler and more maintainablecode compared to the traditional C style. In general, try not to build yourself what hasalready been provided by the standard library.[9] Avoid pointer arithmetic except in very specialized code (such as a memory manager) andfor simple array traversal (e.g., ++p).[10] Do not assume that something laboriously written in C style (avoiding C++ features suchas classes, templates, and exceptions) is more efficient than a shorter alternative (e.g.,using standard-library facilities). Often (but of course not always), the opposite is true.To obey C linkage conventions, a C++ function must be declared to have C linkage (§15.2.5).1.3.4 Suggestions for Java ProgrammersC++ and Java are rather different languages with similar syntaxes.
Their aims are significantly different and so are many of their application domains. Java is not a direct successor to C++ in thesense of a language that can do the same as its predecessor, but better and also more. To use C++well, you need to adopt programming and design techniques appropriate to C++, rather than tryingto write Java in C++. It is not just an issue of remembering to delete objects that you create withnew because you can’t rely on the presence of a garbage collector:[1] Don’t simply mimic Java style in C++; that is often seriously suboptimal for both maintainability and performance.Section 1.3.4Suggestions for Java Programmers21[2]Use the C++ abstraction mechanisms (e.g., classes and templates): don’t fall back to a Cstyle of programming out of a false feeling of familiarity.[3] Use the C++ standard library as a teacher of new techniques and programming styles.[4] Don’t immediately invent a unique base for all of your classes (an Object class).