The C++ Programing Language读书笔记之(1):Advise

本文提供了一系列C++编程建议,覆盖了从基本语法到高级主题如模板、异常处理、继承等各个方面,旨在帮助开发者写出高质量、可维护的代码。

CH  01 Advice:

[1] When you program, you create a concrete representation of the ideas in your solution to some problem. Let the structure of the program reflect those ideas as directly as possible:
    [a] If you can think of ‘‘it’’ as a separate idea, make it a class.
    [b] If you can think of ‘‘it’’ as a separate entity, make it an object of some class.
    [c] If two classes have a common interface, make that interface an abstract class.
    [d] If the implementations of two classes have something significant in common, make that commonality a base class.
    [e] If a class is a container of objects, make it a template.
    [f] If a function implements an algorithm for a container, make it a template function implementing the algorithm for a family of containers.
    [g] If a set of classes, templates, etc., are logically related, place them in a common namespace.
    
[2] When you define either a class that does not implement a mathematical entity like a matrix or a complex number or a lowlevel type such as a linked list:

    [a] Don’t use global data (use members).
    [b] Don’t use global functions.
    [c] Don’t use public data members.
    [d] Don’t use friends, except to avoid [a] or [c].
    [e] Don’t put a ‘‘type field’’ in a class; use virtual functions.

    [f] Don’t use inline functions, except as a significant optimization.


CH 02 Advice:

[1] Don’t panic! All will become clear in time; §2.1.
[2] You don’t have to know every detail of C++ to write good programs; §1.7.
[3] Focus on programming techniques, not on language features; §2.1.


CH 03 Advice:

3.11 Advice [tour2.advice]
[1] Don’t reinvent the wheel; use libraries.
[2] Don’t believe in magic; understand what your libraries do, how they do it, and at what cost
they do it.
[3] When you have a choice, prefer the standard library to other libraries.
[4] Do not think that the standard library is ideal for everything.
[5] Remember to #include the headers for the facilities you use; §3.3.
[6] Remember that standard library facilities are defined in namespace s t d ; §3.3.
[7] Use string rather than char *; §3.5, §3.6.
[8] If in doubt use a rangechecked vector (such as Vec ); §3.7.2.
[9] Prefer vector <T >, list <T >, and map <key ,value > to T []; §3.7.1, §3.7.3, §3.7.4.
[10] When adding elements to a container, use push _ back () or back _ inserter (); §3.7.3, §3.8.
[11] Use push _ back () on avect or rather than realloc () on an array; §3.8.
[12] Catch common exceptions in m a i n (); §3.7.2.


CH 04 Advice:

4.10 Advice [dcl.advice]
[1] Keep scopes small; §4.9.4.
[2] Don’t use the same name in both a scope and an enclosing scope; §4.9.4.
[3] Declare one name (only) per declaration; §4.9.2.
[4] Keep common and local names short, and keep uncommon and nonlocal names longer; §4.9.3.
[5] Avoid similar looking names; §4.9.3.
[6] Maintain a consistent naming style; §4.9.3.
[7] Choose names carefully to reflect meaning rather than implementation; §4.9.3.
[8] Use a typedef to define a meaningful name for a builtin type in cases in which the builtin type used to represent a value might change; §4.9.7.
[9] Use typedef s to define synonyms for types; use enumerations and classes to define new types;§4.9.7.
[10] Remember that every declaration must specify a type (there is no ‘‘implicit i n t ’’); §4.9.1.
[11] Avoid unnecessary assumptions about the numeric value of characters; §4.3.1, §C.6.2.1.
[12] Avoid unnecessary assumptions about the size of integers; §4.6.
[13] Avoid unnecessary assumptions about the range of floatingpoint types; §4.6.
[14] Prefer a plain int over a short int or a long int ; §4.6.
[15] Prefer a double over a float or a long double ; §4.5.
[16] Prefer plain char over signed char and unsigned char ; §C.3.4.
[17] Avoid making unnecessary assumptions about the sizes of objects; §4.6.
[18] Avoid unsigned arithmetic; §4.4.
[19] View signed to unsigned and unsigned to signed conversions with suspicion; §C.6.2.6.
[20] View floating point to integer conversions with suspicion; §C.6.2.6.
[21] View conversions to a smaller type, such as i n t to c h a r , with suspicion; §C.6.2.6.


CH 05 Advice:

5.8 Advice [ptr.advice]
[1] Avoid nontrivial pointer arithmetic; §5.3.
[2] Take care not to write beyond the bounds of an array; §5.3.1.
[3] Use 0 rather than NULL ; §5.1.1.
[4] Use vector and valarray rather than built in (Cstyle) arrays; §5.3.1.
[5] Use s tring rather than zero terminated arrays of c h a r ; §5.3.
[6] Minimize use of plain reference arguments; §5.5.
[7] Avoid void * except in lowlevel code; §5.6.
[8] Avoid nontrivial literals (‘‘magic numbers’’) in code. Instead, define and use symbolic constants; §4.8, §5.4.


CH 06 Advice

6.5 Advice [expr.advice]
[1] Prefer the standard library to other libraries and to ‘‘handcrafted code;’’ §6.1.8.
[2] Avoid complicated expressions; §6.2.3.
[3] If in doubt about operator precedence, parenthesize; §6.2.3.
[4] Avoid explicit type conversion (casts); §6.2.7.
[5] When explicit type conversion is necessary, prefer the more specific cast operators to the Cstyle cast; §6.2.7.
[6] Use theT(e) notation exclusively for welldefined construction; §6.2.8.
[7] Avoid expressions with undefined order of evaluation; §6.2.2.
[8] Avoid goto ; §6.3.4.
[9] Avoid dostatements;§6.3.3.
[10] Don’t declare a variable until you have a value to initialize it with; §6.3.1, §6.3.2.1, §6.3.3.1.
[11] Keep comments crisp; §6.4.
[12] Maintain a consistent indentation style; §6.4.
[13] Prefer defining a member operator new () (§15.6) to replacing the global operator new ();§6.2.6.2.
[14] When reading input, always consider illformed input; §6.1.3.


CH 07 Advice

7.9 Advice [dcl.advice]
[1] Be suspicious of nonconst reference arguments; if you want the function to modify its arguments, use pointers and value return instead; §5.5.
[2] Useconst reference arguments when you need to minimize copying of arguments; §5.5.
[3] Useconst extensively and consistently; §7.2.
[4] Avoid macros; §7.8.
[5] Avoid unspecified numbers of arguments; §7.6.
[6] Don’t return pointers or references to local variables; §7.3.
[7] Use overloading when functions perform conceptually the same task on different types; §7.4.
[8] When overloading on integers, provide functions to eliminate common ambiguities; §7.4.3.
[9] When considering the use of a pointer to function, consider whether a virtual function(§2.5.5) or a template (§2.7.2) would be a better alternative; §7.7.
[10] If you must use macros, use ugly names with lots of capital letters; §7.8.


CH 08 Advice

8.4 Advice [name.advice]
[1] Use namespaces to express logical structure; §8.2.
[2] Place every nonlocal name, except m a i n (), in some namespace; §8.2.
[3] Design a namespace so that you can conveniently use it without accidentally gaining access to unrelated namespaces; §8.2.4.
[4] Avoid very short names for namespaces; §8.2.7.
[5] If necessary, use namespace aliases to abbreviate long namespaces names; §8.2.7.
[6] Avoid placing heavy notational burdens on users of your namespaces; §8.2.2, §8.2.3.
[7] Use the Namespace :: member notation when defining namespace members; §8.2.8.
[8] Use using namespace only for transition or within a local scope; §8.2.9.
[9] Use exceptions to decouple the treatment of ‘‘errors’’ from the code dealing with the ordinary processing; §8.3.3.
[10] Use user-defined rather than built-in types as exceptions; §8.3.2.
[11] Don’t use exceptions when local control structures are sufficient; §8.3.3.1.


CH 09 Advice

9.5 Advice [file.advice]
[1] Use header files to represent interfaces and to emphasize logical structure; §9.1, §9.3.2.
[2] #include a header in the source file that implements its functions; §9.3.1.
[3] Don’t define global entities with the same name and similar but different meanings in different translation units; §9.2.
[4] Avoid noninline function definitions in headers; §9.2.1.
[5] Use #include only at global scope and in namespaces; §9.2.1.
[6] #include only complete declarations; §9.2.1.
[7] Use include guards; §9.3.3.
[8] #include C headers in namespaces to avoid global names; §9.3.2.
[9] Make headers selfcontained; §9.2.3.
[10] Distinguish between users’ interfaces and implementers’ interfaces; §9.3.2.
[11] Distinguish between average users’ interfaces and expert users’ interfaces; §9.3.2.
[12] Avoid nonlocal objects that require runtime initialization in code intended for use as part of non C++ programs; §9.4.1.


CH 10 Advice

10.5 Advice [class.advice]
[1] Represent concepts as classes; §10.1.
[2] Use public data (structs) only when it really is just data and no invariant is meaningful for the data members; §10.2.8.
[3] A concrete type is the simplest kind of class. Where applicable, prefer a concrete type over more complicated classes and over plain data structures; §10.3.
[4] Make a function a member only if it needs direct access to the representation of a class; §10.3.2.
[5] Use a namespace to make the association between a class and its helper functions explicit;§10.3.2.
[6] Make a member function that doesn’t modify the value of its object a c o n s t member function;§10.2.6.
[7] Make a function that needs access to the representation of a class but needn’t be called for a specific object a static member function; §10.2.4.
[8] Use a constructor to establish an invariant for a class; §10.3.1.
[9] If a constructor acquires a resource, its class needs a destructor to release the resource;§10.4.1.
[10] If a class has a pointer member, it needs copy operations (copy constructor and copy assignment);§10.4.4.1.
[11] If a class has a reference member, it probably needs copy operations (copy constructor and copy assignment); §10.4.6.3.
[12] If a class needs a copy operation or a destructor, it probably needs a constructor, a destructor, a copy assignment, and a copy constructor; §10.4.4.1.
[13] Check for selfassignment in copy assignments; §10.4.4.1.
[14] When writing a copy constructor, be careful to copy every element that needs to be copied(beware of default initializers); §10.4.4.1.
[15] When adding a new member to a class, always check to see if there are userdefined constructors that need to be updated to initialize the member; §10.4.6.3.
[16] Use enumerators when you need to define integer constants in class declarations; §10.4.6.1.
[17] Avoid order dependencies when constructing global and namespace objects; §10.4.9.
[18] Use first time switches to minimize order dependencies; §10.4.9.
[19] Remember that temporary objects are destroyed at the end of the full expression in which they are created; §10.4.10.

 

CH11 Advice

11.13 Advice [class.advice]
[1] Define operators primarily to mimic conventional usage; §11.1.
[2] For large operands, use c o n s t reference argument types; §11.6.
[3] For large results, consider optimizing the return; §11.6.
[4] Prefer the default copy operations if appropriate for a class; §11.3.4.
[5] Redefine or prohibit copying if the default is not appropriate for a type; §11.2.2.
[6] Prefer member functions over nonmembers for operations that need access to the representation;§11.5.2.
[7] Prefer nonmember functions over members for operations that do not need access to the representation;§11.5.2.
[8] Use namespaces to associate helper functions with ‘‘their’’ class; §11.2.4.
[9] Use nonmember functions for symmetric operators; §11.3.2.
[10] Use () for subscripting multidimensional arrays; §11.9.
[11] Make constructors that take a single ‘‘size argument’’ e x p l i c i t ; §11.7.1.
[12] For nonspecialized uses, prefer the standard s t r i n g (Chapter 20) to the result of your own exercises; §11.12.
[13] Be cautious about introducing implicit conversions; §11.4.
[14] Use member functions to express operators that require an lvalue as its lefthand operand;§11.3.5.


CH12 Advice

12.6 Advice [derived.advice]
[1] Avoid type fields; §12.2.5.
[2] Use pointers and references to avoid slicing; §12.2.3.
[3] Use abstract classes to focus design on the provision of clean interfaces; §12.3.
[4] Use abstract classes to minimize interfaces; §12.4.2.
[5] Use abstract classes to keep implementation details out of interfaces; §12.4.2.
[6] Use virtual functions to allow new implementations to be added without affecting user code; §12.4.1.
[7] Use abstract classes to minimize recompilation of user code; §12.4.2.
[8] Use abstract classes to allow alternative implementations to coexist; §12.4.3.
[9] A class with a virtual function should have a virtual destructor; §12.4.2.
[10] An abstract class typically doesn’t need a constructor; §12.4.2.
[11] Keep the representations of distinct concepts distinct; §12.4.1.1.


CH13 Advice

13.8 Advice [temp.advice]
[1] Use templates to express algorithms that apply to many argument types; §13.3.
[2] Use templates to express containers; §13.2.
[3] Provide specializations for containers of pointers to minimize code size; §13.5.
[4] Always declare the general form of a template before specializations; §13.5.
[5] Declare a specialization before its use; §13.5.
[6] Minimize a template definition’s dependence on its instantiation contexts; §13.2.5, §C.13.8.
[7] Define every specialization you declare; §13.5.
[8] Consider if a template needs specializations for Cstyle strings and arrays; §13.5.2.
[9] Parameterize with a policy object; §13.4.
[10] Use specialization and overloading to provide a single interface to implementations of the same concept for different types; §13.5.
[11] Provide a simple interface for simple cases and use overloading and default arguments to express less common cases; §13.5, §13.4.
[12] Debug concrete examples before generalizing to a template; §13.2.1.
[13] Remember to export template definitions that need to be accessible from other translation units; §13.7.
[14] Separately compile large templates and templates with nontrivial context dependencies; §13.7.
[15] Use templates to express conversions but define those conversions very carefully; §13.6.3.1.
[16] Where necessary, constrain template arguments using a constraint() member function; §13.9[16].
[17] Use explicit instantiation to minimize compile time and link time; §C.13.10.
[18] Prefer a template over derived classes when runtime efficiency is at a premium; §13.6.1.
[19] Prefer derived classes over a template if adding new variants without recompilation is important;§13.6.1.
[20] Prefer a template over derived classes when no common base can be defined; §13.6.1.
[21] Prefer a template over derived classes when builtin types and structures with compatibility constraints are important; §13.6.1.


CH14 Advice

14.11 Advice [except.advice]
[1] Use exceptions for error handling; §14.1, §14.5, §14.9.
[2] Don’t use exceptions where more local control structures will suffice; §14.1.
[3] Use the ‘‘resource allocation is initialization’’ technique to manage resources; §14.4.
[4] Not every program needs to be exception safe; §14.4.3.
[5] Use ‘‘resource allocation is initialization’’ and exception handlers to maintain invariants;§14.3.2.
[6] Minimize the use of tryblocks. Use ‘‘resource acquisition is initialization’’ instead of explicit handler code; §14.4.
[7] Not every function needs to handle every possible error; §14.9.
[8] Throw an exception to indicate failure in a constructor; §14.4.6.
[9] Avoid throwing exceptions from copy constructors; §14.4.6.1.
[10] Avoid throwing exceptions from destructors; §14.4.7.
[11] Have m a i n () catch and report all exceptions; §14.7.
[12] Keep ordinary code and errorhandling code separate; §14.4.5, §14.5.
[13] Be sure that every resource acquired in a constructor is released when throwing an exception in that constructor; §14.4.
[14] Keep resource management hierarchical; §14.4.
[15] Use exceptionspecifications for major interfaces; §14.9.
[16] Beware of memory leaks caused by memory allocated by n e w not being released in case of an exception; §14.4.1, §14.4.2, §14.4.4.
[17] Assume that every exception that can be thrown by a function will be thrown; §14.6.
[18] Don’t assume that every exception is derived from class e x c e p t i o n ; §14.10.
[19] A library shouldn’t unilaterally terminate a program. Instead, throw an exception and let a caller decide; §14.1.
[20] A library shouldn’t produce diagnostic output aimed at an end user. Instead, throw an exception and let a caller decide; §14.1.
[21] Develop an errorhandling strategy early in a design; §14.9.



CH15 Advice

15.7 Advice [hier.advice]
[1] Use ordinary multiple inheritance to express a union of features; §15.2, §15.2.5.
[2] Use multiple inheritance to separate implementation details from an interface; §15.2.5.
[3] Use a virtual base to represent something common to some, but not all, classes in a hierarchy;§15.2.5.
[4] Avoid explicit type conversion (casts); §15.4.5.
[5] Use dynamic_cast where class hierarchy navigation is unavoidable; §15.4.1.
[6] Prefer dynamic_ca t over typeid ; §15.4.4.
[7] Prefer private to protected ; §15.3.1.1.
[8] Don’t declare data members protected ; §15.3.1.1.
[9] If a class defines operator delete (), it should have a virtual destructor; §15.6.
[10] Don’t call virtual functions during construction or destruction; §15.4.3.
[11] Use explicit qualification for resolution of member names sparingly and preferably use it in overriding functions; §15.2.1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值