google_c++编程风格指南
google的C++编程风格(Google C++ Style Guide)
Google C++ Style GuideBenjy WeinbergerCraig SilversteinGregory EitzmannMark MentovaiTashana LandrayEach style point has a summary for which additional information is available by toggling the accompanying arrow button that looks this way: ▶. You may toggle all summaries with the big arrow button:▶ Toggle all summariesTable of ContentsHeader Files The #define Guard Header File Dependencies InlineFunctions The -inl.h Files Function Parameter OrderingNames and Order of IncludesScoping Namespaces Nested Classes Nonmember, Static Member, and Global Functions Local Variables Global Variables Classes Doing Work in Constructors Default Constructors ExplicitConstructors Copy Constructors Structs vs. ClassesInheritance Multiple Inheritance Interfaces OperatorOverloading Access Control Declaration Order Write ShortFunctionsGoogle-SpecificMagicSmart PointersOther C++ Features Reference Arguments Function Overloading Default Arguments Variable-Length Arrays and alloca()Friends Exceptions Run-Time Type Information (RTTI)Casting Streams Preincrement and Predecrement Use of const Integer Types64-bit Portability Preprocessor Macros0 and NULL sizeof BoostNaming General Naming Rules File Names Type Names Variable Names Constant Names Function Names NamespaceNames Enumerator Names Macro Names Exceptions toNaming RulesComments Comment Style File Comments Class Comments Function Comments Variable Comments Implementation CommentsPunctuation, Spelling and Grammar TODO Comments Formatting Line Length Non-ASCII Characters Spaces vs. TabsFunction Declarations and Definitions Function CallsConditionals Loops and Switch Statements Pointer andReference Expressions Boolean Expressions Return ValuesVariable and Array Initialization Preprocessor DirectivesClass Format Initializer Lists Namespace FormattingHorizontal Whitespace Vertical WhitespaceExisting Non-conformant Code Windows CodeExceptions tothe RulesOverviewImportant NoteDisplaying Hidden Details in this Guide▶ This style guide contains many details that are initially hidden from view. They are marked by the triangle icon, which you see here on your left. Click it now. You should see "Hooray" appear below.BackgroundC++ is the main development language used by many of Google'sopen-source projects. As every C++ programmer knows, the language has many powerful features, but this power brings with it complexity, which in turn can make code more bug-prone and harder to read and maintain.The goal of this guide is to manage this complexity by describing in detail the dos and don'ts of writing C++ code. These rules exist to keep the code base manageable while still allowing coders to use C++ language features productively.Style, also known as readability, is what we call the conventions that govern our C++ code. The term Style is a bit of a misnomer, since these conventions cover far more than just source file formatting.One way in which we keep the code base manageable is by enforcing consistency. It is very important that any programmer be able to look at another's code and quickly understand it. Maintaining a uniform style and following conventions means that we can more easily use "pattern-matching" to infer what various symbols are and what invariants are true about them. Creating common, required idioms and patterns makes code much easier to understand. In some cases there might be good arguments for changingcertain style rules, but we nonetheless keep things as they are in order to preserve consistency.Another issue this guide addresses is that of C++ feature bloat. C++ is a huge language with many advanced features. In some cases we constrain, or even ban, use of certain features. We do this to keep code simple and to avoid the various common errors and problems that these features can cause. This guide lists these features and explains why their use is restricted.Open-source projects developed by Google conform to the requirements in this guide.Note that this guide is not a C++ tutorial: we assume that the reader is familiar with the language.Header FilesIn general, every .cc file should have an associated .h file. There are some common exceptions, such as unittests and small .cc files containing just a main() function.Correct use of header files can make a huge difference to the readability, size and performance of your code.The following rules will guide you through the various pitfalls of using header files.The #define Guard▶ All header files should have #define guards to prevent multiple inclusion. The format of the symbol name should be <PROJECT>_<PATH>_<FILE>_H_.Header File Dependencies▶ Use forward declarations to minimize use of #include in .h files.Inline Functions▶ Define functions inline only when they are small, say, 10 lines or less.The -inl.h Files▶ You may use file names with a -inl.h suffix to define complex inline functions when needed.Function Parameter Ordering▶ When defining a function, parameter order is: inputs, then outputs.Names and Order of Includes▶ Use standard order for readability and to avoid hidden dependencies: C library, C++ library, other libraries' .h, your project's .h.ScopingNamespaces▶ Unnamed namespaces in .cc files are encouraged. With named namespaces, choose the name based on the project, and possibly its path. Do not use a using-directive.Nested Classes▶ Although you may use public nested classes when they are part of an interface, consider a namespace to keep declarations out of the global scope.Nonmember, Static Member, and Global Functions▶ Prefer nonmember functions within a namespace or static member functions to global functions; use completely global functions rarely.Local Variables▶ Place a function's variables in the narrowest scope possible, and initialize variables in the declaration.Global Variables▶ Global variables of class types are forbidden. Global variables of built-in types are allowed, although non-const globals are forbidden in threaded code. Global variables should never be initialized with the return value of a function.ClassesClasses are the fundamental unit of code in C++. Naturally, we use them extensively. This section lists the main dos and don'ts you should follow when writing a class.Doing Work in Constructors▶ Do only trivial initialization in a constructor. If at all possible, use an Init() method for non-trivial initialization.Default Constructors▶ You must define a default constructor if your class defines member variables and has no other constructors. Otherwise the compiler will do it for you, badly.Explicit Constructors▶ Use the C++ keyword explicit for constructors with one argument.Copy Constructors▶ Use copy constructors only when your code needs to copy a class; most do not need to be copied and so should use DISALLOW_COPY_AND_ASSIGN.Structs vs. Classes▶ Use a struct only for passive objects that carry data; everything else is a class.Inheritance▶ Composition is often more appropriate than inheritance. When using inheritance, make it public.Multiple Inheritance▶ Only very rarely is multiple implementation inheritance actually useful. We allow multiple inheritance only when at most one of the base classes has an implementation; all other base classes must be pure interface classes tagged with the Interface suffix.Interfaces▶ Classes that satisfy certain conditions are allowed, but not required, to end with an Interface suffix.Operator Overloading▶ Do not overload operators except in rare, special circumstances.Access Control▶ Make all data members private, and provide access to them through accessor functions as needed. Typically a variable would be called foo_ and the accessor function foo(). You may also want a mutator function set_foo().Declaration Order▶ Use the specified order of declarations within a class: public: before private:, methods before data members (variables), etc.Write Short Functions▶ Prefer small and focused functions.Google-Specific MagicThere are various tricks and utilities that we use to make C++ code more robust, and various ways we use C++ that may differ from what you see elsewhere.Smart Pointers▶ If you actually need pointer semantics, scoped_ptr is great. You should only use std::tr1::shared_ptr under very specific conditions, such as when objects need to be held by STL containers. You should never use auto_ptr.Other C++ FeaturesReference Arguments▶ All parameters passed by reference must be labeled const.Function Overloading▶ Use overloaded functions (including constructors) only in cases where input can be specified in different types that contain the same information. Do not use function overloading to simulate default function parameters.Default Arguments▶ We do not allow default function parameters.Variable-Length Arrays and alloca()▶ We do not allow variable-length arrays or alloca().Friends▶ We allow use of friend classes and functions, within reason.Exceptions▶ We do not use C++ exceptions.Run-Time Type Information (RTTI)▶ We do not use Run Time Type Information (RTTI).Casting▶ Use C++ casts like static_cast<>(). Do not use other cast formats like int y = (int)x; or int y = int(x);.Streams▶ Use streams only for logging.Preincrement and Predecrement▶ Use prefix form (++i) of the increment and decrement operators with iterators and other template objects.Use of const▶ We strongly recommend that you use const whenever it makes sense to do so.Integer Types▶ Of the built-in C++ integer types, the only one used is int. If a program needs a variable of a different size, use a precise-width integer type from <stdint.h>, such as int16_t.64-bit Portability▶ Code should be 64-bit and 32-bit friendly. Bear in mind problems of printing, comparisons, and structure alignment.Preprocessor Macros▶ Be very cautious with macros. Prefer inline functions, enums, and const variables to macros.0 and NULL▶ Use 0 for integers, 0.0 for reals, NULL for pointers, and '\0' for chars.sizeof▶ Use sizeof(varname) instead of sizeof(type) whenever possible.Boost▶ Use only approved libraries from the Boost library collection.NamingThe most important consistency rules are those that govern naming. The style of a name immediately informs us what sort of thing the named entity is: a type, a variable, a function, a constant, a macro, etc., without requiring us to search for the declaration of that entity. The pattern-matching engine in our brains relies a great deal on these naming rules.Naming rules are pretty arbitrary, but we feel that consistency is more important than individual preferences in this area, so regardless of whether you find them sensible or not, the rules are the rules.General Naming Rules▶ Function names, variable names, and filenames should be descriptive; eschew abbreviation. Types and variables should be nouns, while functions should be "command" verbs.File Names▶ Filenames should be all lowercase and can include underscores (_) or dashes (-). Follow the convention that your project uses.Type Names▶ Type names start with a capital letter and have a capital letter for each new word, with no underscores: MyExcitingClass, MyExcitingEnum.Variable Names▶ Variable names are all lowercase, with underscores between words. Class member variables have trailing underscores. For instance:my_exciting_local_variable, my_exciting_member_variable_.Constant Names▶ Use a k followed by mixed case: kDaysInAWeek.Function Names▶ Regular functions have mixed case; accessors and mutators match the name of the variable: MyExcitingFunction(), MyExcitingMethod(),my_exciting_member_variable(), set_my_exciting_member_variable().Namespace Names▶ Namespace names are all lower-case, and based on project names and possibly their directory structure: google_awesome_project.Enumerator Names▶ Enumerators should be all uppercase with underscores between words:MY_EXCITING_ENUM_VALUE.Macro Names▶ You're not really going to define a macro, are you? If you do, they're like this: MY_MACRO_THAT_SCARES_SMALL_CHILDREN.Exceptions to Naming Rules▶ If you are naming something that is analogous to an existing C or C++ entity then you can follow the existing naming convention scheme.CommentsThough a pain to write, comments are absolutely vital to keeping our code readable. The following rules describe what you should comment and where. But remember: while comments are very important, the best code isself-documenting. Giving sensible names to types and variables is much better than using obscure names that you must then explain through comments. When writing your comments, write for your audience: the next contributor who will need to understand your code. Be generous — the next one may be you!Comment Style▶ Use either the // or /* */ syntax, as long as you are consistent.File Comments▶ Start each file with a copyright notice, followed by a description of the contents of the file.Class Comments▶ Every class definition should have an accompanying comment that describes what it is for and how it should be used.Function Comments▶ Declaration comments describe use of the function; comments at the definition of a function describe operation.Variable Comments▶ In general the actual name of the variable should be descriptive enough to give a good idea of what the variable is used for. In certain cases, more comments are required.Implementation Comments▶ In your implementation you should have comments in tricky, non-obvious, interesting, or important parts of your code.Punctuation, Spelling and Grammar▶ Pay attention to punctuation, spelling, and grammar; it is easier to readwell-written comments than badly written ones.TODO Comments▶ Use TODO comments for code that is temporary, a short-term solution, or good-enough but not perfect.FormattingCoding style and formatting are pretty arbitrary, but a project is much easier to follow if everyone uses the same style. Individuals may not agree with every aspect of the formatting rules, and some of the rules may take some getting used to, but it is important that all project contributors follow the style rules so that they can all read and understand everyone's code easily.Line Length▶ Each line of text in your code should be at most 80 characters long.Non-ASCII Characters▶ Non-ASCII characters should be rare, and must use UTF-8 formatting.Spaces vs. Tabs▶ Use only spaces, and indent 2 spaces at a time.Function Declarations and Definitions▶ Return type on the same line as function name, parameters on the same line if they fit.Function Calls▶ On one line if it fits; otherwise, wrap arguments at the parenthesis.Conditionals▶ Prefer no spaces inside parentheses. The else keyword belongs on a new line.Loops and Switch Statements▶ Switch statements may use braces for blocks. Empty loop bodies should use {} or continue.Pointer and Reference Expressions▶ No spaces around period or arrow. Pointer operators do not have trailing spaces.Boolean Expressions▶ When you have a boolean expression that is longer than the standard line length, be consistent in how you break up the lines.Return Values▶ Do not surround the return expression with parentheses.Variable and Array Initialization▶ Your choice of = or ().Preprocessor Directives▶ Preprocessor directives should not be indented but should instead start at the beginning of the line.Class Format▶ Sections in public, protected and private order, each indented one space.Initializer Lists▶ Constructor initializer lists can be all on one line or with subsequent lines indented four spaces.Namespace Formatting▶ The contents of namespaces are not indented.Horizontal Whitespace▶ Use of horizontal whitespace depends on location. Never put trailing whitespace at the end of a line.Vertical Whitespace▶ Minimize use of vertical whitespace.Exceptions to the RulesThe coding conventions described above are mandatory. However, like all good rules, these sometimes have exceptions, which we discuss here. Existing Non-conformant Code▶ You may diverge from the rules when dealing with code that does not conform to this style guide.Windows Code▶ Windows programmers have developed their own set of coding conventions, mainly derived from the conventions in Windows headers and other Microsoft code. We want to make it easy for anyone to understand your code, so we have a single set of guidelines for everyone writing C++ on any platform. Parting WordsUse common sense and BE CONSISTENT.If you are editing code, take a few minutes to look at the code around you and determine its style. If they use spaces around their if clauses, you should, too. If their comments have little boxes of stars around them, make your comments have little boxes of stars around them too.The point of having style guidelines is to have a common vocabulary of coding so people can concentrate on what you are saying, rather than on how you are saying it. We present global style rules here so people know the vocabulary. But local style is also important. If code you add to a file looks drastically different from the existing code around it, the discontinuity throws readers out of their rhythm when they go to read it. Try to avoid this.OK, enough writing about writing code; the code itself is much more interesting. Have fun!Benjy WeinbergerCraig SilversteinGregory EitzmannMark MentovaiTashana Landray。
Google C++ Style Guide 谷歌 C++编码风格指南
谷歌C++编程风格指南[版本:3.180]Benjy WeinbergerCraig SilversteinGregory EitzmannMark MentovaiTashana Landray翻译:郑州大学赵峻(仅供参考)目录一、背景 (1)二、正文 (1)1.头文件(Header Files) (1)1.1#define保护(#include guard) (1)1.2头文件的依赖关系(Header File Dependencies) (2)1.3内联函数(Inline Functions) (2)1.4内联头文件(The –inl.h Files) (3)1.5函数参数次序(Function Parameter Ordering) (3)1.6包含的命名和次序(Names and Order of includes) (3)2.作用域(Scoping) (4)2.1名称空间(Namespaces) (4)2.2类嵌套(Nested Classes) (6)2.3外部函数、静态成员函数和全局函数(Nonmember, Static Member, andGlobal Functions) (7)2.4局部变量(Local Variables) (7)2.5静态变量和全局变量(Static and Global Variables) (8)3.类(Classes) (9)3.1在构造函数中完成工作(Doing Work in Constructors) (9)3.2默认构造函数(Default Constructor) (9)3.3显式构造函数(Explicit Constructors) (10)3.4复制构造函数(Copy Constructos) (10)3.5结构体与类(Structs vs Classes) (11)3.6继承(Inheritance) (11)3.7多重继承(Multiple Inheritance) (12)3.8接口(Interface) (12)3.9运算符重载(Operator Overloading) (13)3.10访问控制(Access Control) (13)3.11声明次序(Declaration Order) (13)3.12定义简短函数(Write Short Functions) (14)4.谷歌经验技巧(Google-Specific Magic) (14)4.1智能指针(Smart Pointers) (14)4.2CPPlint (15)5.其他C++特性(Other C++ Fetures) (15)5.1引用参数(Reference Arguments) (15)5.2函数重载(Function Overloading) (15)5.3默认参数(Default Arguments) (16)5.4可变长度数组和内存申请(Variable-Length Arrays and alloca()) 165.5友元(Friends) (17)5.6异常处理(Excpetions) (17)5.7运行时类型信息(Run-Time Type Information, RTTI) (18)5.8类型转换(Casting) (18)5.9流(Streams) (19)5.10前置自增和前置自减(Preincrement and Predecrement) (20)5.11const修饰符的使用(Use of const) (20)5.12整型类型(Integer Types) (21)5.1364位兼容性(64-bit Portability) (22)5.14预处理宏(Preprocessor Macros) (22)5.150和空(0 and NULL) (23)5.16存储容量运算符(sizeof) (23)5.17增强库(Boost) (23)5.18C++ 0x库 (24)6.命名(Naming) (24)6.1一般命名规则(General Naming Rules) (24)6.2文件命名(File Names) (25)6.3类型命名(Type Names) (26)6.4变量命名(Variable Names) (26)6.5常量命名(Constant Names) (27)6.6函数命名(Function Names): (27)6.7名称空间的命名(Namespace Names) (27)6.8枚举器的命名(Enumerator Names) (27)6.9宏命名(Macro Names) (28)6.10命名规则的例外情况(Exceptions to Naming Rules) (28)7.注释(Comments) (28)7.1注释风格(Comment Style) (28)7.2文件注释(File Comments) (28)7.3类注释(Class Comments) (29)7.4函数注释(Function Comments) (29)7.5变量注释(Variable Comments) (30)7.6以空、真/假、数字作为参数(NULL、true/false、1,2,3...) .. (31)7.7注释的标点、拼写和语法 (Punctuation,Spelling and Gramma) (31)7.8TODO注释(TODO Comments) (32)7.9废弃性注释(Deprecation Comments) (32)8.编码格式(Formatting) (32)8.1行长度(Line Length) (32)8.2非ASCII码字符(Non-ASCII Characters) (33)8.3窗格还是制表符(Spaces vs. Tabs) (33)8.4函数声明与定义(Function Declarations and Definitions) (33)8.5函数调用(Function Calls) (34)8.6条件语句(Conditonals) (34)8.7循环和多分支语句(Loops and Switch Statements) (36)8.8指针与引用表达式(Pointer and Reference Expressions) (36)8.9布尔表达式(Boolean Expressions) (37)8.10返回值(Return Values) (37)8.11变量和数组的初始化(Variable and Array Initialization) (37)8.12预处理指令(Preprocessor Directives) (37)8.13类格式(Class Format) (37)8.14构造函数初始化列表(Constructor Initializer Lists) (38)8.15名称空间格式(Namespace Formatting) (38)8.16水平空白(Horizontal Whitespace) (38)8.17垂直空白(Vertical Whitespace) (40)9.本规则的例外情况(Exceptons to the Rules) (40)9.1现存不一致代码(Existing Non-conformant Code) (40)9.2Windows代码(Windows Code) (40)10.结束语(Parting Words) (41)一、背景C++ 是很多谷歌开源项目的主开发语言。
Google的Objective-C编码规范
Google的Objective-C编码规范总览背景知识Objective-C是一个C语言的扩展语言,非常动态,非常的“面向对象”,它被设计成既拥有复杂的面向对象设计理念又可以轻松使用与阅读的语言,也是Mac OS X和iPhone开发的首选语言。
Cocoa是Mac OS X的主要应用框架,提供迅速开发各种功能的Mac OS X应用的Objective-C 类集合。
Apple已经有一个很好也被广泛接受的Objective-C的编程规范,Google也有类似的C++编程规范,这份Objective-C编程规范很自然是Apple和Google的共同推荐的组合。
所以,在阅读本规范前,确保你已经阅读了:Apple's Cocoa Coding GuidelinesGoogle's Open Source C++ Style Guide注意所有已在Google的C++编程规范里的禁用条款在Objective-C里也适用,除非本文档明确指出反对意见。
本文档旨在描述可供可适用于所有Mac OS X代码的Objective-C(包括Objective-C++)编码规范和实践。
规范中的许多条款已经改进也不断的被其他的项目和团队所证明其指导性。
Google的相关开源项目都遵守此规范。
Google已经发布了一份作为Google Toolbox for Mac project (文档中简称为GTM)的组成部分的遵守本规范的开源代码。
这份开放代码也是本文很好的例证(原文看不太懂--Code meant to be shared across different projects is a good candidate to be included in this repository. )注意本文不是Objective-C的教学指南,我们假设读者已经了解语言。
如果你是一个Objective-C 的初学者或需要重温,请阅读The Objective-C Programming Language .示例人们说一个例子胜过千言万语,所以就让我们用例子来让你感受以下编码规范的风格,留间距,命名等等。
google c++常用命名规则
一、概述Google C++编程规范是一系列关于C++编程的最佳实践和规范的指南。
在Google内部,C++是一种非常重要的编程语言,因此编写规范和最佳实践对于确保代码的质量、可读性和可维护性至关重要。
在Google C++编程规范中,命名规则是其中一个非常重要的部分。
良好的命名规则能够使得代码更加清晰易懂,便于团队协作和后续维护。
本文将介绍Google C++中常用的命名规则。
二、命名规则1. 使用驼峰命名法在Google C++编程规范中,推荐使用驼峰命名法(Camel Case)来命名变量、函数和类。
驼峰命名法是一种命名约定,其中单词的首字母大写,并且不使用下划线或者其他分隔符。
这种命名规则能够使得代码更加易读,并且符合C++语言的传统。
示例:```cppint myVariable;void myFunction();class MyClass;```2. 命名方式在Google C++编程规范中,推荐使用描述性的名称。
具体来说,变量、函数和类的名字应该能够清晰地表达其用途和含义。
这样做可以使得代码更加易读和易于理解,帮助其他开发人员快速了解代码的含义和作用。
示例:```cppint numStudents; // 表示学生数量的变量void calculateAverage(); // 计算平均值的函数class BinaryTree; // 二叉树类```3. 命名空间在Google C++编程规范中,命名空间应该使用小写字母,且不能使用下划线或者其他分隔符。
命名空间应该能够清晰地表达其内容和作用。
示例:```cppnamespace mynamespace {// ...}```4. 常量命名在Google C++编程规范中,常量命名应该全部大写,并且使用下划线分隔单词。
这样做可以使得常量在代码中更加显眼,并且帮助其他开发人员快速识别常量的存在。
示例:```cppconst int MAX_NUMBER = 100;const double PI = 3.xxx;```5. 文件名命名在Google C++编程规范中,文件名应该全部小写,并且可以使用下划线分隔单词。
Google_C++编程风格指南(推荐)
Google C++编程风格指南(一)背景Google的开源项目大多使用C++开发。
每一个C++程序员也都知道,C++具有很多强大的语言特性,但这种强大不可避免的导致它的复杂,这种复杂会使得代码更易于出现bug、难于阅读和维护。
本指南的目的是通过详细阐述在C++编码时要怎样写、不要怎样写来规避其复杂性。
这些规则可在允许代码有效使用C++语言特性的同时使其易于管理。
风格,也被视为可读性,主要指称管理C++代码的习惯。
使用术语风格有点用词不当,因为这些习惯远不止源代码文件格式这么简单。
使代码易于管理的方法之一是增强代码一致性,让别人可以读懂你的代码是很重要的,保持统一编程风格意味着可以轻松根据“模式匹配”规则推断各种符号的含义。
创建通用的、必需的习惯用语和模式可以使代码更加容易理解,在某些情况下改变一些编程风格可能会是好的选择,但我们还是应该遵循一致性原则,尽量不这样去做。
本指南的另一个观点是C++特性的臃肿。
C++是一门包含大量高级特性的巨型语言,某些情况下,我们会限制甚至禁止使用某些特性使代码简化,避免可能导致的各种问题,指南中列举了这类特性,并解释说为什么这些特性是被限制使用的。
由Google开发的开源项目将遵照本指南约定。
注意:本指南并非C++教程,我们假定读者已经对C++非常熟悉。
头文件通常,每一个.cc文件(C++的源文件)都有一个对应的.h文件(头文件),也有一些例外,如单元测试代码和只包含main()的.cc文件。
正确使用头文件可令代码在可读性、文件大小和性能上大为改观。
下面的规则将引导你规避使用头文件时的各种麻烦。
1. #define的保护所有头文件都应该使用#define防止头文件被多重包含(multiple inclusion),命名格式当是:<PROJECT>_<PATH>_<FILE>_H_为保证唯一性,头文件的命名应基于其所在项目源代码树的全路径。
Google计算机C++编码规范中文版
结论:一个比轳得当的处理觃则是,丌要内联超过 10 行的函数。对亍枂极函数应慎重对待,枂极函数往 往比其表面看起来要长,因为有一些隐式成员和基类枂极函数(如果有的话)被调用!
使代码易亍管理的方法乊一是增强代码一致性,让别人可以诺懂你的代码是徆重要的,保持统一编程风格 意味着可以轱松根据“模式匹配”觃则推断各种符号的吨义。创建通用的、必需的习惯用诧和模式可以使 代码更加容易理解,在某些情冴下改发一些编程风格可能会是好的选择,但我们迓是应该遵循一致性原则, 尽量丌返样去做。
在头文件如何做到使用类 Foo 而无需访问类的定义? 1) 将数据成员类型声明为 Foo *戒 Foo &; 2) 参数、迒回值类型为 Foo 的函数叧是声明(但丌定义实现); 3) 静态数据成员的类型可以被声明为 Foo,因为静态数据成员的定义在类定义乊外。 另一方面,如果你的类是 Foo 的子类,戒者吨有类型为 Foo 的非静态数据成员,则必须为乊包吨头文件。
另一有用的处理觃则:内联那些包吨循环戒 switch 诧句的函数是得丌偿失的,除非在大多数情冴下,返些 循环戒 switch 诧句从丌执行。
重要的是,虚函数和递归函数即使被声明为内联的也丌一定就是内联函数。通常,递归函数丌应该被声明 为内联的(译者注:递归调用堆栈的展开幵丌像循环那么简单,比如递归局数在编译时可能是未知的,大 多数编译器都丌支持内联递归函数)。枂极函数内联的主要原因是其定义在类的定义中,为了方便抑戒是对 其行为给出文档。
Google C++ 编码风格精简
用 reinterpret_cast 指针类型和整型或其它指针之间进行不安全的相互转换. 仅在你对所做一切了然于心时使用 dynamic_cast 测试代码以外不要使用. 除非是单元测试, 如果你需要在运行时确定类型信息, 说明有 设计缺陷
}
8.只在记录日志时使用流
9.对迭代器和模板类型, 使用前置自增 (自减).对简单数值 (非对象)无所谓
8.当重载一个虚函数, 在衍生类中把它明确的声明为 virtual
9.只在以下情况我们才允许多重继承: 最多只有一个基类是非抽象类; 其它基类都是以Interface为后缀的纯接口类
10.接口是指满足特定条件的类, 这些类以 Interface 为后缀 (不强制).
11.尽量不要重载运算符
12.数据成员在任何情况下都必须是私有的, 并根据需要提供相应的存取函数
10.强烈建议你在任何可能的情况下都要使用 const
{
如果函数不会修改传入的引用或指针类型参数, 该参数应声明为 const.
尽可能将函数声明为 const. 访问函数应该总是 const. 其他不会修改任何数据成员, 未调用非 const 函数, 不会返回数据成员非 const 指针或引用的函数也应该声明成 const.
2.文件名要全部小写, 可以包含下划线 (_) 或连字符 (-). 按项目约定来.
3.类型名称的每个单词首字母均大写, 不包含下划线: MyExcitingClass, MyExcitingEnum.
4.变量名一律小写, 单词之间用下划线连接. 类的成员变量以下划线结尾:my_local_variable,my_member_variable_
14.使用宏时要非常谨慎, 尽量以内联函数, 枚举和常量代替之{来自不要在 .h 文件中定义宏
google_c++编程风格(高清版)
Google C++编程风格指南edisonpeng 整理2009/3/25Preface背景 (3)头文件 (4)作用域 (8)C++类 (13)智能指针和其他C++特性 (20)命名约定 (32)代码注释 (38)格式 (44)规则之例外 (57)背景Google的项目大多使用C++开发。
每一个C++程序员也都知道,C++具有很多强大的语言特性,但这种强大不可避免的导致它的复杂,而复杂性会使得代码更容易出现bug、难于阅读和维护。
本指南的目的是通过详细阐述如何进行C++编码来规避其复杂性,使得代码在有效使用C++语言特性的同时还易于管理。
使代码易于管理的方法之一是增强代码一致性,让别人可以读懂你的代码是很重要的,保持统一编程风格意味着可以轻松根据“模式匹配”规则推断各种符号的含义。
创建通用的、必需的习惯用语和模式可以使代码更加容易理解,在某些情况下改变一些编程风格可能会是好的选择,但我们还是应该遵循一致性原则,尽量不这样去做。
本指南的另一个观点是C++特性的臃肿。
C++是一门包含大量高级特性的巨型语言,某些情况下,我们会限制甚至禁止使用某些特性使代码简化,避免可能导致的各种问题,指南中列举了这类特性,并解释说为什么这些特性是被限制使用的。
注意:本指南并非C++教程,我们假定读者已经对C++非常熟悉。
头文件通常,每一个.cc文件(C++的源文件)都有一个对应的.h文件(头文件),也有一些例外,如单元测试代码和只包含main()的.cc文件。
正确使用头文件可令代码在可读性、文件大小和性能上大为改观。
下面的规则将引导你规避使用头文件时的各种麻烦。
1. #define保护所有头文件都应该使用#define防止头文件被多重包含(multiple inclusion),命名格式为:<PROJECT>_<PATH>_<FILE>_H_为保证唯一性,头文件的命名应基于其所在项目源代码树的全路径。
Google编程风格指南(一)
Google编程风格指南(一)
0. 扉页
0.1 译者前言
Google 经常会发布一些开源项目, 意味着会接受来自其他代码贡献者的代码. 但是如果代码贡献者的编程风格与Google 的不一致, 会给代码阅读者和其他代码提交者造成不小的困扰. Google 因此发布了这份自己的编程风格指南, 使所有提交代码的人都能获知Google 的编程风格.
翻译初衷:
规则的作用就是避免混乱. 但规则本身一定要权威, 有说服力, 并且是理性的. 我们所见过的大部分编程规范, 其内容或不够严谨, 或阐述过于简单, 或带有一定的武断性. Google 保持其一贯的严谨精神, 5 万汉字的指南涉及广泛, 论证严密. 我们翻译该系列指南的主因也正是其严谨性. 严谨意味着指南的价值不仅仅局限于它罗列出的规范, 更具参考意义的是它为了列出规范而做的谨慎权衡过程.
指南不仅列出你要怎么做, 还告诉你为什么要这么做, 哪些情况下可以不这么做, 以及如何权衡其利弊. 其他团队未必要完全遵照指南亦步亦趋, 如前面所说, 这份指南是Google 根据自身实际情况打造的, 适用于其主导的开源项目. 其他团队可以参照该指南, 或从中汲取灵感, 建立适合自身实际情况的规范.
我们在翻译的过程中, 收获颇多. 希望本系列指南中文版对你同样能有所帮助.
我们翻译时也是尽力保持严谨, 但水平所限, bug 在所难免. 有任何意见或建议, 可与我们取得联系.
中文版和英文版一样, 使用 Artistic License/GPL 开源许可.
中文版修订历史:
2015-08 : 热心的清华大学同学@lilinsanity 完善了「类」章节以及其它一些小章节。
至此,对Google CPP Style Guide 4.45 的翻译正式竣工。
Google C++编程风格指南
Google C++编程风格指南(一)背景Google的开源项目大多使用C++开发。
每一个C++程序员也都知道,C++具有很多强大的语言特性,但这种强大不可避免的导致它的复杂,这种复杂会使得代码更易于出现bug、难于阅读和维护。
本指南的目的是通过详细阐述在C++编码时要怎样写、不要怎样写来规避其复杂性。
这些规则可在允许代码有效使用C++语言特性的同时使其易于管理。
风格,也被视为可读性,主要指称管理C++代码的习惯。
使用术语风格有点用词不当,因为这些习惯远不止源代码文件格式这么简单。
使代码易于管理的方法之一是增强代码一致性,让别人可以读懂你的代码是很重要的,保持统一编程风格意味着可以轻松根据“模式匹配”规则推断各种符号的含义。
创建通用的、必需的习惯用语和模式可以使代码更加容易理解,在某些情况下改变一些编程风格可能会是好的选择,但我们还是应该遵循一致性原则,尽量不这样去做。
本指南的另一个观点是C++特性的臃肿。
C++是一门包含大量高级特性的巨型语言,某些情况下,我们会限制甚至禁止使用某些特性使代码简化,避免可能导致的各种问题,指南中列举了这类特性,并解释说为什么这些特性是被限制使用的。
由Google开发的开源项目将遵照本指南约定。
注意:本指南并非C++教程,我们假定读者已经对C++非常熟悉。
头文件通常,每一个.cc文件(C++的源文件)都有一个对应的.h文件(头文件),也有一些例外,如单元测试代码和只包含main()的.cc文件。
正确使用头文件可令代码在可读性、文件大小和性能上大为改观。
下面的规则将引导你规避使用头文件时的各种麻烦。
1.#define的保护所有头文件都应该使用#define防止头文件被多重包含(multiple inclusion),命名格式当是:<PROJECT>_<PATH>_<FILE>_H_为保证唯一性,头文件的命名应基于其所在项目源代码树的全路径。
Google C++ 风格指南-中文版
1.2. 头文件依赖
Tip 能用前置声明的地方尽量不使用 #include.
当一个头文件被包含的同时也引入了新的依赖, 一旦该头文件被修改, 代码就会被重新编译. 如果这个头文件又包含 了其他头文件, 这些头文件的任何改变都将导致所有包含了该头文件的代码被重新编译. 因此, 我们倾向于减少包含 头文件, 尤其是在头文件中包含头文件. 使用前置声明可以显著减少需要包含的头文件数量. 举例说明: 如果头文件中用到类 File, 但不需要访问 File 类的 声明, 头文件中只需前置声明 class File; 而无须 #include "file/base/file.h". 不允许访问类的定义的前提下, 我们在一个头文件中能对类 Foo 做哪些操作?
注意: 本指南并非 C++ 教程, 我们假定读者已经对 C++ 非常熟悉.
1. 头文件 — Google C++ Style Guide
Page 1 of 3
1. 头文件
通常每一个 .cc 文件都有一个对应的 .h 文件. 也有一些常见例外, 如单元测试代码和只包含 main() 函数的 .cc 文 件. 正确使用头文件可令代码在可读性、文件大小和性能上大为改观. 下面的规则将引导你规避使用头文件时的各种陷阱.
1.3. 内联函数
Tip 只有当函数只有 10 行甚至更少时才将其定义为内联函数.
定义: 当函数被声明为内联函数之后, 编译器会将其内联展开, 而不是按通常的函数调用机制进行调用.
优点: 当函数体比较小的时候, 内联该函数可以令目标代码更加高效. 对于存取函数以及其它函数体比较短, 性能关键 的函数, 鼓励使用内联.
Google C++ 编程规范
Google C++ Style GuideImportant NoteDisplaying Hidden Details in this GuideThis style guide contains many details that are initially hidden from view. They are marked by the triangle icon, which you see here on your left. Click it now. You should see "Hooray" appear below.Hooray! Now you know you can expand points to get more details. Alternatively, there's an "expand all" at the top of this document. BackgroundC++ is the main development language used by many of Google's open-source projects. As every C++ programmer knows, the language has many powerful features, but this power brings with it complexity, which in turn can make code more bug-prone and harder to read and maintain.The goal of this guide is to manage this complexity by describing in detail the dos and don'ts of writing C++ code. These rules exist to keep the code base manageable while still allowing coders to use C++ language features productively.Style, also known as readability, is what we call the conventions that govern our C++ code. The term Style is a bit of a misnomer, since these conventions cover far more than just source file formatting.One way in which we keep the code base manageable is by enforcing consistency. It is very important that any programmer be able to look at another's code and quickly understand it. Maintaining a uniform style and following conventions means that we can more easily use "pattern-matching" to infer what various symbols are and what invariants are true about them. Creating common, required idioms and patterns makes code much easier to understand. In some cases there might be good arguments for changing certain style rules, but we nonetheless keep things as they are in order to preserve consistency.Another issue this guide addresses is that of C++ feature bloat. C++ is a huge language with many advanced features. In some cases we constrain, or even ban, use of certain features. We do this to keep code simple and to avoid the various common errors and problems that these features can cause. This guide lists these features and explains why their use is restricted.Open-source projects developed by Google conform to the requirements in this guide.Note that this guide is not a C++ tutorial: we assume that the reader is familiar with the language.Header FilesIn general, every .cc file should have an associated .h file. There are some common exceptions, such as unittests and small .cc files containing just a main() function.Correct use of header files can make a huge difference to the readability, size and performance of your code.The following rules will guide you through the various pitfalls of using header files.The #define GuardAll header files should have #define guards to prevent multiple inclusion. The format of the symbol name should be <PROJECT>_<PATH>_<FILE>_H_.To guarantee uniqueness, they should be based on the full path in a project's source tree. For example, the file foo/src/bar/baz.h in projectHeader File DependenciesDon't use an #include when a forward declaration would suffice.When you include a header file you introduce a dependency that will cause your code to be recompiled whenever the header file changes. If your header file includes other header files, any change to those files will cause any code that includes your header to be recompiled. Therefore, we prefer to minimize includes, particularly includes of header files in other header files.You can significantly reduce the number of header files you need to include in your own header files by using forward declarations. For example, if your header file uses the File class in ways that do not require access to the declaration of the File class, your header file can just forward declare class File; instead of having to #include "file/base/file.h".How can we use a class Foo in a header file without access to its definition?●We can declare data members of type Foo* or Foo&.●We can declare (but not define) functions with arguments, and/or return values, of type Foo. (One exception is if an argument Foo orconst Foo&has a non-explicit, one-argument constructor, in which case we need the full definition to support automatic type conversion.)●We can declare static data members of type Foo. This is because static data members are defined outside the class definition.On the other hand, you must include the header file for Foo if your class subclasses Foo or has a data member of type Foo.Sometimes it makes sense to have pointer (or better, scoped_ptr) members instead of object members. However, this complicates code readability and imposes a performance penalty, so avoid doing this transformation if the only purpose is to minimize includes in header files.Of course, .cc files typically do require the definitions of the classes they use, and usually have to include several header files.Note:If you use a symbol Foo in your source file, you should bring in a definition for Foo yourself, either via an #include or via a forward declaration. Do not depend on the symbol being brought in transitively via headers not directly included. One exception is if Foo is used in , it's ok to #include (or forward-declare) Foo in myfile.h, instead of .Inline FunctionsDefine functions inline only when they are small, say, 10 lines or less.Definition:You can declare functions in a way that allows the compiler to expand them inline rather than calling them through the usual function call mechanism.Pros:Inlining a function can generate more efficient object code, as long as the inlined function is small. Feel free to inline accessors and mutators, and other short, performance-critical functions.Cons:Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache.Decision:A decent rule of thumb is to not inline a function if it is more than 10 lines long. Beware of destructors, which are often longer than they appear because of implicit member- and base-destructor calls!Another useful rule of thumb: it's typically not cost effective to inline functions with loops or switch statements (unless, in the common case, the loop or switch statement is never executed).It is important to know that functions are not always inlined even if they are declared as such; for example, virtual and recursive functions are not normally inlined. Usually recursive functions should not be inline. The main reason for making a virtual function inline is to place its definition in the class, either for convenience or to document its behavior, e.g., for accessors and mutators.The -inl.h FilesYou may use file names with a -inl.h suffix to define complex inline functions when needed.The definition of an inline function needs to be in a header file, so that the compiler has the definition available for inlining at the call sites. However, implementation code properly belongs in .cc files, and we do not like to have much actual code in .h files unless there is a readability or performance advantage.If an inline function definition is short, with very little, if any, logic in it, you should put the code in your .h file. For example, accessors and mutators should certainly be inside a class definition. More complex inline functions may also be put in a .h file for the convenience of the implementer and callers, though if this makes the .h file too unwieldy you can instead put that code in a separate -inl.h file. This separates the implementation from the class definition, while still allowing the implementation to be included where necessary.Another use of -inl.h files is for definitions of function templates. This can be used to keep your template definitions easy to read.Do not forget that a -inl.h file requires a #define guard just like any other header file.Function Parameter OrderingWhen defining a function, parameter order is: inputs, then outputs.Parameters to C/C++ functions are either input to the function, output from the function, or both. Input parameters are usually values or const references, while output and input/output parameters will be non-const pointers. When ordering function parameters, put all input-only parameters before any output parameters. In particular, do not add new parameters to the end of the function just because they are new; place new input-only parameters before the output parameters.This is not a hard-and-fast rule. Parameters that are both input and output (often classes/structs) muddy the waters, and, as always, consistency with related functions may require you to bend the rule.Names and Order of IncludesUse standard order for readability and to avoid hidden dependencies: C library, C++ library, other libraries' .h, your project's .h.All of a project's header files should be listed as descendants of the project's source directory without use of UNIX directory shortcuts . (the1.dir2/foo2.h (preferred location — see details below).2. C system files.3.C++ system files.4.Other libraries' .h files.5.Your project's .h files.The preferred ordering reduces hidden dependencies. We want every header file to be compilable on its own. The easiest way to achieve this is to make sure that every one of them is the first .h file #include d in some .cc.dir/ and dir2/foo2.h are often in the same directory (e.g. base/basictypes_ and base/basictypes.h), but can be in different directories too.Within each section it is nice to order the includes alphabetically.ScopingNamespacesUnnamed namespaces files are encouraged. With named namespaces, choose the name based on the project, and possibly its path. Do not use a using-directive.Definition:Namespaces subdivide the global scope into distinct, named scopes, and so are useful for preventing name collisions in the global scope. Pros:Namespaces provide a (hierarchical) axis of naming, in addition to the (also hierarchical) name axis provided by classes.For example, if two different projects have a class Foo in the global scope, these symbols may collide at compile time or at runtime. If each project places their code in a namespace, project1::Foo and project2::Foo are now distinct symbols that do not collide.Cons:Namespaces can be confusing, because they provide an additional (hierarchical) axis of naming, in addition to the (also hierarchical) name axis provided by classes.Use of unnamed spaces in header files can easily cause violations of the C++ One Definition Rule (ODR).Decision:Use namespaces according to the policy described below.Unnamed Namespaces∙static member functions rather than as members of an unnamed namespace. Terminate the unnamed namespace as shown, with a comment // namespace.∙Do not use unnamed namespaces in .h files.Named NamespacesNamed namespaces should be used as follows:∙Namespaces wrap the entire source file after includes, gflags definitions/declarations, and forward declarations of classes from otherstd is undefined behavior, i.e., not portable. To declare entities from the standard library, include the appropriate header file.∙∙∙transitively #included by them, should avoid defining aliases, as part of the general goal of keeping public APIs as small as possible.Nested ClassesAlthough you may use public nested classes when they are part of an interface, consider a namespace to keep declarations out of the global scope.Definition:scope rather than polluting the outer scope with the class name. Nested classes can be forward declared within the enclosing class and then defined in the .cc file to avoid including the nested class definition in the enclosing class declaration, since the nested class definition is usually only relevant to the implementation.Cons:Nested classes can be forward-declared only within the definition of the enclosing class. Thus, any header file manipulating a Foo::Bar* pointer will have to include the full class declaration for Foo.Decision:Do not make nested classes public unless they are actually part of the interface, e.g., a class that holds a set of options for some method. Nonmember, Static Member, and Global FunctionsPrefer nonmember functions within a namespace or static member functions to global functions; use completely global functions rarely. Pros:Nonmember and static member functions can be useful in some situations. Putting nonmember functions in a namespace avoids polluting the global namespace.Cons:Nonmember and static member functions may make more sense as members of a new class, especially if they access external resources or have significant dependencies.Decision:Sometimes it is useful, or even necessary, to define a function not bound to a class instance. Such a function can be either a static member or a nonmember function. Nonmember functions should not depend on external variables, and should nearly always exist in a namespace. Rather than creating classes only to group static member functions which do not share static data, use namespaces instead.Functions defined in the same compilation unit as production classes may introduce unnecessary coupling and link-time dependencies when directly called from other compilation units; static member functions are particularly susceptible to this. Consider extracting a new class, or placing the functions in a namespace possibly in a separate library.If you must define a nonmember function and it is only needed in its .cc file, use an unnamed namespace or static linkage (eg static int Foo() {...}) to limit its scope.Local VariablesPlace a function's variables in the narrowest scope possible, and initialize variables in the declaration.C++ allows you to declare variables anywhere in a function. We encourage you to declare them in as local a scope as possible, and as close to the first use as possible. This makes it easier for the reader to find the declaration and see what type the variable is and what it was initializedStatic and Global VariablesStatic or global variables of class type are forbidden: they cause hard-to-find bugs due to indeterminate order of construction and destruction.Objects with static storage duration, including global variables, static variables, static class member variables, and function static variables, must be Plain Old Data (POD): only ints, chars, floats, or pointers, or arrays/structs of POD.The order in which class constructors and initializers for static variables are called is only partially specified in C++ and can even change from build to build, which can cause bugs that are difficult to find. Therefore in addition to banning globals of class type, we do not allow static POD variables to be initialized with the result of a function, unless that function (such as getenv(), or getpid()) does not itself depend on any other globals.Likewise, the order in which destructors are called is defined to be the reverse of the order in which the constructors were called. Since constructor order is indeterminate, so is destructor order. For example, at program-end time a static variable might have been destroyed, but code still running -- perhaps in another thread -- tries to access it and fails. Or the destructor for a static 'string' variable might be run prior to the destructor for another variable that contains a reference to that string.As a result we only allow static variables to contain POD data. This rule completely disallows vector (use C arrays instead), or string (use const char []).If you need a static or global variable of a class type, consider initializing a pointer (which will never be freed), from either your main() function or from pthread_once(). Note that this must be a raw pointer, not a "smart" pointer, since the smart pointer's destructor will have the order-of-destructor issue that we are trying to avoid.ClassesClasses are the fundamental unit of code in C++. Naturally, we use them extensively. This section lists the main dos and don'ts you should follow when writing a class.Doing Work in ConstructorsIn general, constructors should merely set member variables to their initial values. Any complex initialization should go in an explicit Init() method.Definition:It is possible to perform initialization in the body of the constructor.Pros:Convenience in typing. No need to worry about whether the class has been initialized or not.Cons:The problems with doing work in constructors are:∙There is no easy way for constructors to signal errors, short of using exceptions (which are forbidden).∙If the work fails, we now have an object whose initialization code failed, so it may be an indeterminate state.∙If the work calls virtual functions, these calls will not get dispatched to the subclass implementations. Future modification to your class can quietly introduce this problem even if your class is not currently subclassed, causing much confusion.∙If someone creates a global variable of this type (which is against the rules, but still), the constructor code will be called before main(),functions, attempt to raise errors, access potentially uninitialized global variables, etc.Default ConstructorsYou must define a default constructor if your class defines member variables and has no other constructors. Otherwise the compiler will do it for you, badly.Definition:The default constructor is called when we new a class object with no arguments. It is always called when calling new[] (for arrays). Pros:Initializing structures by default, to hold "impossible" values, makes debugging much easier.Cons:Extra work for you, the code writer.Decision:If your class defines member variables and has no other constructors you must define a default constructor (one that takes no arguments). It should preferably initialize the object in such a way that its internal state is consistent and valid.The reason for this is that if you have no other constructors and do not define a default constructor, the compiler will generate one for you. This compiler generated constructor may not initialize your object sensibly.If your class inherits from an existing class but you add no new member variables, you are not required to have a default constructor. Explicit ConstructorsUse the C++ keyword explicit for constructors with one argument.Definition:Normally, if a constructor takes one argument, it can be used as a conversion. For instance, if you define Foo::Foo(string name) and then pass a string to a function that expects a Foo, the constructor will be called to convert the string into a Foo and will pass the Foo to your function for you. This can be convenient but is also a source of trouble when things get converted and new objects created without you meaning them to. Declaring a constructor explicit prevents it from being invoked implicitly as a conversion.Pros:Avoids undesirable conversions.Cons:None.Decision:We require all single argument constructors to be explicit. Always put explicit in front of one-argument constructors in the class definition: explicit Foo(string name);The exception is copy constructors, which, in the rare cases when we allow them, should probably not be explicit. Classes that are intended to be transparent wrappers around other classes are also exceptions. Such exceptions should be clearly marked with comments.Copy ConstructorsProvide a copy constructor and assignment operator only when necessary. Otherwise, disable them with DISALLOW_COPY_AND_ASSIGN.Definition:The copy constructor and assignment operator are used to create copies of objects. The copy constructor is implicitly invoked by the compiler in some situations, e.g. passing objects by value.Pros:Copy constructors make it easy to copy objects. STL containers require that all contents be copyable and assignable. Copy constructors can be more efficient than CopyFrom()-style workarounds because they combine construction with copying, the compiler can elide them in some contexts, and they make it easier to avoid heap allocation.Cons:Implicit copying of objects in C++ is a rich source of bugs and of performance problems. It also reduces readability, as it becomes hard to track which objects are being passed around by value as opposed to by reference, and therefore where changes to an object are reflected. Decision:Few classes need to be copyable. Most should have neither a copy constructor nor an assignment operator. In many situations, a pointer or reference will work just as well as a copied value, with better performance. For example, you can pass function parameters by reference or pointer instead of by value, and you can store pointers rather than objects in an STL container.If your class needs to be copyable, prefer providing a copy method, such as CopyFrom() or Clone(), rather than a copy constructor, because such methods cannot be invoked implicitly. If a copy method is insufficient in your situation (e.g. for performance reasons, or because your class needs to be stored by value in an STL container), provide both a copy constructor and assignment operator.If your class does not need a copy constructor or assignment operator, you must explicitly disable them. To do so, add dummy declarations for the copy constructor and assignment operator in the private:section of your class, but do not provide any corresponding definition (so that any attempt to use them results in a link error).Structs vs. ClassesUse a struct only for passive objects that carry data; everything else is a class.The struct and class keywords behave almost identically in C++. We add our own semantic meanings to each keyword, so you should use the appropriate keyword for the data-type you're defining.Structs should be used for passive objects that carry data, and may have associated constants, but lack any functionality other than access/setting the data members. The accessing/setting of fields is done by directly accessing the fields rather than through method invocations. Methods should not provide behavior but should only be used to set up the data members, e.g., constructor, destructor, Initialize(),Reset(), Validate().If more functionality is required, a class is more appropriate. If in doubt, make it a class.For consistency with STL, you can use struct instead of class for functors and traits.Note that member variables in structs and classes have different naming rules.InheritanceComposition is often more appropriate than inheritance. When using inheritance, make it public.Definition:When a sub-class inherits from a base class, it includes the definitions of all the data and operations that the parent base class defines. In practice, inheritance is used in two major ways in C++: implementation inheritance, in which actual code is inherited by the child, and interfacecompile-time declaration, you and the compiler can understand the operation and detect errors. Interface inheritance can be used to programmatically enforce that a class expose a particular API. Again, the compiler can detect errors, in this case, when a class does not define a necessary method of the API.Cons:For implementation inheritance, because the code implementing a sub-class is spread between the base and the sub-class, it can be more difficult to understand an implementation. The sub-class cannot override functions that are not virtual, so the sub-class cannot change implementation. The base class may also define some data members, so that specifies physical layout of the base class.Decision:All inheritance should be public. If you want to do private inheritance, you should be including an instance of the base class as a member instead.Do not overuse implementation inheritance. Composition is often more appropriate. Try to restrict use of inheritance to the "is-a" case: Bar subclasses Foo if it can reasonably be said that Bar "is a kind of"Foo.Make your destructor virtual if necessary. If your class has virtual methods, its destructor should be virtual.Limit the use of protected to those member functions that might need to be accessed from subclasses. Note that data members should be private.When redefining an inherited virtual function, explicitly declare it virtual in the declaration of the derived class. Rationale: If virtual is omitted, the reader has to check all ancestors of the class in question to determine if the function is virtual or not.Multiple InheritanceOnly very rarely is multiple implementation inheritance actually useful. We allow multiple inheritance only when at most one of the basethose that have an implementation.Pros:you can usually find a different, more explicit, and cleaner solution.Decision:Multiple inheritance is allowed only when all superclasses, with the possible exception of the first one, are pure interfaces. In order to ensure that they remain pure interfaces, they must end with the Interface suffix.Note:There is an exception to this rule on Windows.InterfacesClasses that satisfy certain conditions are allowed, but not required, to end with an Interface suffix.Definition:A class is a pure interface if it meets the following requirements:∙It has only public pure virtual ("= 0") methods and static methods (but see below for destructor).∙It may not have non-static data members.∙It need not have any constructors defined. If a constructor is provided, it must take no arguments and it must be protected.∙If it is a subclass, it may only be derived from classes that satisfy these conditions and are tagged with the Interface suffix.An interface class can never be directly instantiated because of the pure virtual method(s) it declares. To make sure all implementations of the interface can be destroyed correctly, they must also declare a virtual destructor (in an exception to the first rule, this should not be pure). See Stroustrup, The C++ Programming Language, 3rd edition, section 12.4 for details.Pros:Tagging a class with the Interface suffix lets others know that they must not add implemented methods or non static data members. This isconsidered an implementation detail that shouldn't be exposed to clients.Decision:A class may end with Interface only if it meets the above requirements. We do not require the converse, however: classes that meet the above requirements are not required to end with Interface.Operator OverloadingDo not overload operators except in rare, special circumstances.Definition:A class can define that operators such as + and / operate on the class as if it were a built-in type.Pros:Can make code appear more intuitive because a class will behave in the same way as built-in types (such as int). Overloaded operators are more playful names for functions that are less-colorfully named, such as Equals() or Add(). For some template functions to work correctly, you may need to define operators.Cons:While operator overloading can make code more intuitive, it has several drawbacks:∙It can fool our intuition into thinking that expensive operations are cheap, built-in operations.∙It is much harder to find the call sites for overloaded operators. Searching for Equals()is much easier than searching for relevant invocations of ==.∙Some operators work on pointers too, making it easy to introduce bugs. Foo + 4 may do one thing, while &Foo + 4 does something totally different. The compiler does not complain for either of these, making this very hard to debug.Overloading also has surprising ramifications. For instance, if a class overloads unary operator&, it cannot safely be forward-declared. Decision:In general, do not overload operators. The assignment operator (operator=), in particular, is insidious and should be avoided. You can define functions like Equals()and CopyFrom()if you need them. Likewise, avoid the dangerous unary operator&at all costs, if there's any possibility the class might be forward-declared.However, there may be rare cases where you need to overload an operator to interoperate with templates or "standard" C++ classes (such as operator<<(ostream&, const T&) for logging). These are acceptable if fully justified, but you should try to avoid these whenever possible. In particular, do not overload operator== or operator< just so that your class can be used as a key in an STL container; instead, you should create equality and comparison functor types when declaring the container.Some of the STL algorithms do require you to overload operator==, and you may do so in these cases, provided you document why.See also Copy Constructors and Function Overloading.。
C++编程风格指南
C++编程风格指南[译]Google C++编程风格指南(⼋)[完]Fox @ 2008-07-23 15:42:32, $62翻译C++开始评论本⽂最早(2008/07/23)发表于:C++博客原⽂地址:Google C++ Style Guide规则之例外前⾯说明的编码习惯基本是强制性的,但所有优秀的规则都允许例外。
1. 现有不统⼀代码(Existing Non-conformant Code)对于现有不符合既定编程风格的代码可以⽹开⼀⾯。
当你修改使⽤其他风格的代码时,为了与代码原有风格保持⼀致可以不使⽤本指南约定。
如果不放⼼可以与代码原作者或现在的负责⼈员商讨,记住,⼀致性包括原有的⼀致性。
1. Windows代码(Windows Code)Windows程序员有⾃⼰的编码习惯,主要源于Windows的⼀些头⽂件和其他Microsoft代码。
我们希望任何⼈都可以顺利读懂你的代码,所以针对所有平台的C++编码给出⼀个单独的指导⽅案。
如果你⼀直使⽤Windows编码风格的,这⼉有必要重申⼀下某些你可能会忘记的指南(译者注,我怎么感觉像在被洗脑:D):1) 不要使⽤匈⽛利命名法(Hungarian notation,如定义整型变量为iNum),使⽤Google命名约定,包括对源⽂件使⽤.cc扩展名;2) Windows定义了很多原有内建类型的同义词(译者注,这⼀点,我也很反感),如DWORD、HANDLE等等,在调⽤Windows API时这是完全可以接受甚⾄⿎励的,但还是尽量使⽤原来的C++类型,例如,使⽤const TCHAR *⽽不是LPCTSTR;3) 使⽤Microsoft Visual C++进⾏编译时,将警告级别设置为3或更⾼,并将所有warnings当作errors处理;4) 不要使⽤#pragma once;作为包含保护,使⽤C++标准包含保护,包含保护的⽂件路径包含到项⽬树顶层(译者注,#include);5) 除⾮万不得已,否则不使⽤任何不标准的扩展,如#pragma和__declspec,允许使⽤__declspec(dllimport)和__declspec(dllexport),但必须通过DLLIMPORT和DLLEXPORT等宏,以便其他⼈在共享使⽤这些代码时容易放弃这些扩展。
google公开的c++编程规范
▽ All header files should have #define guards to prevent multiple inclusion. The format of the symbol name should be <PROJECT>_<PATH>_<FILE>_H_. To guarantee uniqueness, they should be based on the full path in a project's source tree. For example, the file foo/src/bar/baz.h in project foo should have the following guard:
Background
C++ is the main development language used by many of Google's open-source projects. As every C++ programmer knows, the language has many powerful features, but this power brings with it complexity, which in turn can make code more bug-prone and harder to read and maintain. The goal of this guide is to manage this complexity by describing in detail the dos and don'ts of writing C++ code. These rules exist to keep the code base manageable while still allowing coders to use C++ language features productively. Style, also known as readability, is what we call the conventions that govern our C++ code. The term Style is a bit of a misnomer, since these conventions cover far more than just source file formatting. One way in which we keep the code base manageable is by enforcing consistency. It is very important that any programmer be able to look at another's code and quickly understand it. Maintaining a uniform style and following conventions means that we can more easily use "pattern-matching" to infer what various symbols are and what invariants are true about them. Creating common, required idioms and patterns makes code much easier to understand. In some cases there might be good arguments for changing certain style rules, but we nonetheless keep things as they are in order to preserve consistency. Another issue this guide addresses is that of C++ feature bloat. C++ is a huge language with many advanced features. In some cases we constrain, or even ban, use of certain features. We do this to keep code simple and to avoid the various common errors and problems that these features can cause. This guide lists these features and explains why their use is restricted. Open-source projects developed by Google conform to the requirements in this guide. Note that this guide is not a C++ tutorial: we assume that the reader is familiar with the language.
Google的C++编程规范
本指南的目的是通过详细阐述 C++ 注意事项来驾驭其复杂性. 这些规则在保证代码易于管理的同时, 高效使用 C++ 的语言特性.风格, 亦被称作可读性, 也就是指导 C++ 编程的约定. 使用术语 “风格” 有些用词不当, 因为这些习惯远不止源代码文件格式化这么简单.使代码易于管理的方法之一是加强代码一致性. 让任何程序员都可以快速读懂你的代码这点非常重要. 保持统一编程风格并遵守约定意味着可以很容易根据 “模式匹配” 规则来推断各种标识符的含义. 创建通用, 必需的习惯用语和模式可以使代码更容易理解. 在一些情况下可能有充分的理由改变某些编程风格, 但我们还是应该遵循一致性原则,尽量不这么做.本指南的另一个观点是 C++ 特性的臃肿. C++ 是一门包含大量高级特性的庞大语言. 某些情况下, 我们会限制甚至禁止使用某些特性. 这么做是为了保持代码清爽, 避免这些特性可能导致的各种问题. 指南中列举了这类特性, 并解释为什么这些特性被限制使用.Google 主导的开源项目均符合本指南的规定.注意: 本指南并非 C++ 教程, 我们假定读者已经对 C++ 非常熟悉.« C++ 风格指南 - 内容目录 :: Contents :: 1. 头文件 »© Copyright . Created using Sphinx 1.1.3.© Copyright . Created using Sphinx 1.1.3.定义:Boost 库集是一个广受欢迎, 经过同行鉴定, 免费开源的 C++ 库集.优点:Boost代码质量普遍较高, 可移植性好, 填补了 C++ 标准库很多空白, 如型别的特性, 更完善的绑定器, 更好的智能指针, 同时还提供了TR1 (标准库扩展) 的实现.缺点:某些 Boost 库提倡的编程实践可读性差, 比如元编程和其他高级模板技术, 以及过度 “函数化” 的编程风格.结论:为了向阅读和维护代码的人员提供更好的可读性, 我们只允许使用 Boost 一部分经认可的特性子集. 目前允许使用以下库:Compressed Pair : boost/compressed_pair.hppPointer Container : boost/ptr_container (序列化除外)Array : boost/array.hppThe Boost Graph Library (BGL) : boost/graph (序列化除外)Property Map : boost/property_map.hppIterator中处理迭代器定义的部分 : boost/iterator/iterator_adaptor.hpp,boost/iterator/iterator_facade.hpp, 以及boost/function_output_iterator.hpp我们正在积极考虑增加其它 Boost 特性, 所以列表中的规则将不断变化.« 4. 来自 Google 的奇技 :: Contents :: 6. 命名约定 »© Copyright . Created using Sphinx 1.1.3.。
google C++编程规范
Important NoteDisplaying Hidden Details in this GuideBackgroundC++ is the main development language used by many of Google's open-source projects. As every C++ programmer knows, the language has many powerful features, but this power brings with it complexity, which in turn can make code more bug-prone and harder to read and maintain.The goal of this guide is to manage this complexity by describing in detail the dos and don'ts of writing C++ code. These rules exist to keep the code base manageable while still allowing coders to use C++ language features productively.Style, also known as readability, is what we call the conventions that govern our C++ code. The term Style is a bit of a misnomer, since these conventions cover far more than just source file formatting.One way in which we keep the code base manageable is by enforcing consistency. It is very important that any programmer be able to look at another's code and quickly understand it. Maintaining a uniform style and following conventions means that we can more easily use "pattern-matching" to infer what various symbols are and what invariants are true about them. Creating common, required idioms and patterns makes code much easier to understand. Insome cases there might be good arguments for changing certain style rules, but we nonetheless keep things as they are in order to preserve consistency.Another issue this guide addresses is that of C++ feature bloat. C++ is a huge language with many advanced features. In some cases we constrain, or even ban, use of certain features. We do this to keep code simple and to avoid the various common errors and problems that these features can cause. This guide lists these features and explains why their use is restricted.Open-source projects developed by Google conform to the requirements in this guide.Note that this guide is not a C++ tutorial: we assume that the reader is familiar with the language.Header FilesIn general, every .cc file should have an associated .h file. There are some common exceptions, such as unittests and small .cc files containing just a main() function.Correct use of header files can make a huge difference to the readability, size and performance of your code.The following rules will guide you through the various pitfalls of using header files.The #define GuardHeader File Dependencies•We can declare data members of type Foo* or Foo&.•We can declare (but not define) functions with arguments, and/orreturn values, of type Foo. (One exception is if anargument Foo or const Foo& has a non-explicit, one-argumentconstructor, in which case we need the full definition to supportautomatic type conversion.)•We can declare static data members of type Foo. This is becausestatic data members are defined outside the class definition.On the other hand, you must include the header file for Foo if your class subclasses Foo or has a data member of type Foo.Sometimes it makes sense to have pointer (or better, scoped_ptr) members instead of object members. However, this complicates code readability and imposes a performance penalty, so avoid doing this transformation if the only purpose is to minimize includes in header files.Of course, .cc files typically do require the definitions of the classes they use, and usually have to include several header files.Note: If you use a symbol Foo in your source file, you should bring in a definitionfor Foo yourself, either via an #include or via a forward declaration. Do not depend on the symbol being brought in transitively via headers not directly included. One exception isif Foo is used in , it's ok to #include (or forward-declare) Foo in myfile.h, instead of .Inline FunctionsThe -inl.h FilesIf an inline function definition is short, with very little, if any, logic in it, you should put the code in your .h file. For example, accessors and mutators should certainly be inside a class definition. More complex inline functions may also be put in a .h file for the convenience of the implementer and callers, though if this makes the .h file too unwieldy you can instead put that code in a separate -inl.h file. This separates the implementation from the class definition, while still allowing the implementation to be included where necessary.Another use of -inl.h files is for definitions of function templates. This can be used to keep your template definitions easy to read.Do not forget that a -inl.h file requires a #define guard just like any other header file.Function Parameter OrderingNames and Order of IncludesIn dir/, whose main purpose is to implement or test the stuff in dir2/foo2.h, order your includes as follows:1. dir2/foo2.h (preferred location — see details below).2. C system files.3. C++ system files.4. Other libraries' .h files.5. Your project's .h files.The preferred ordering reduces hidden dependencies. We want every header file to be compilable on its own. The easiest way to achieve this is to make sure that every one of them is the first.h file #include d in some .cc.dir/ and dir2/foo2.h are often in the same directory(e.g.base/basictypes_ and base/basictypes.h), but can be in different directories too.Within each section it is nice to order the includes alphabetically.For example, the includesin google-awesome-project/src/foo/internal/ might look like this:ScopingNamespacesNamespaces provide a (hierarchical) axis of naming, in addition to the (also hierarchical) name axis provided by classes.For example, if two different projects have a class Foo in the global scope, these symbols may collide at compile time or at runtime. If each project places their code in anamespace,project1::Foo and project2::Foo are now distinct symbols that do not collide.Cons:Namespaces can be confusing, because they provide an additional (hierarchical) axis of naming, in addition to the (also hierarchical) name axis provided by classes.Use of unnamed spaces in header files can easily cause violations of the C++ One Definition Rule (ODR).Decision:Use namespaces according to the policy described below.Unnamed NamespacesHowever, file-scope declarations that are associated with a particularclass may be declared in that class as types, static data members orstatic member functions rather than as members of an unnamednamespace. Terminate the unnamed namespace as shown, with acomment // namespace.•Do not use unnamed namespaces in .h files.Named NamespacesNamed namespaces should be used as follows:The typical .cc file might have more complex detail, including the need to reference classes in other namespaces.Note that an alias in a .h file is visible to everyone #including that file, so public headers (those available outside a project) and headers transitively #included by them, should avoid defining aliases, as part of the general goal of keeping public APIs as small as possible.Nested ClassesPros:This is useful when the nested (or member) class is only used by the enclosing class; making it a member puts it in the enclosing class scope rather than polluting the outer scope with the class name. Nested classes can be forward declared within the enclosing class and then defined in the .cc file to avoid including the nested class definition in the enclosing class declaration, since the nested class definition is usually only relevant to the implementation.Cons:Nested classes can be forward-declared only within the definition of the enclosing class. Thus, any header file manipulating a Foo::Bar* pointer will have to include the full class declaration for Foo.Decision:Do not make nested classes public unless they are actually part of the interface, e.g., a class that holds a set of options for some method.Nonmember, Static Member, and Global FunctionsDecision:Sometimes it is useful, or even necessary, to define a function not bound to a class instance. Such a function can be either a static member or a nonmember function. Nonmember functions should not depend on external variables, and should nearly always exist in a namespace. Rather than creating classes only to group static member functions which do not share static data, use namespaces instead.Functions defined in the same compilation unit as production classes may introduce unnecessary coupling and link-time dependencies when directly called from other compilation units; static member functions are particularly susceptible to this. Consider extracting a new class, or placing the functions in a namespace possibly in a separate library.If you must define a nonmember function and it is only needed in its .cc file, use an unnamed namespace or static linkage (eg static int Foo() {...}) to limit its scope.Local VariablesNote that gcc implements for (int i = 0; i < 10; ++i) correctly (the scope of i is only the scope of the for loop), so you can then reuse i in another for loop in the same scope. It also correctly scopes declarations in if and while statements, e.g.There is one caveat: if the variable is an object, its constructor is invoked every time it enters scope and is created, and its destructor is invoked every time it goes out of scope.It may be more efficient to declare such a variable used in a loop outside that loop:Static and Global VariablesClassesClasses are the fundamental unit of code in C++. Naturally, we use them extensively. This section lists the main dos and don'ts you should follow when writing a class.Doing Work in Constructors•There is no easy way for constructors to signal errors, short of usingexceptions (which are forbidden).•If the work fails, we now have an object whose initialization codefailed, so it may be an indeterminate state.•If the work calls virtual functions, these calls will not get dispatched tothe subclass implementations. Future modification to your class canquietly introduce this problem even if your class is not currentlysubclassed, causing much confusion.•If someone creates a global variable of this type (which is against therules, but still), the constructor code will be called before main(),possibly breaking some implicit assumptions in the constructor code.For instance, gflags will not yet have been initialized.Decision:If your object requires non-trivial initialization, consider having anexplicit Init() method. In particular, constructors should not call virtual functions, attempt to raise errors, access potentially uninitialized global variables, etc.Default ConstructorsDefinition:The default constructor is called when we new a class object with no arguments. It is always called when calling new[] (for arrays).Pros:Initializing structures by default, to hold "impossible" values, makes debugging much easier.Cons:Extra work for you, the code writer.Decision:If your class defines member variables and has no other constructors you must define a default constructor (one that takes no arguments). It should preferably initialize the object in such a way that its internal state is consistent and valid.The reason for this is that if you have no other constructors and do not define a default constructor, the compiler will generate one for you. This compiler generated constructor may not initialize your object sensibly.If your class inherits from an existing class but you add no new member variables, you are not required to have a default constructor.Explicit ConstructorsThe exception is copy constructors, which, in the rare cases when we allow them, should probably not be explicit. Classes that are intended to be transparent wrappers around other classes are also exceptions. Such exceptions should be clearly marked with comments.Copy ConstructorsThen, in class Foo:Structs vs. ClassesInheritanceComposition is often more appropriate than inheritance. When using inheritance, makeit public.Definition:When a sub-class inherits from a base class, it includes the definitions of all the data and operations that the parent base class defines. In practice, inheritance is used in two major ways in C++: implementation inheritance, in which actual code is inherited by the child,and interface inheritance, in which only method names are inherited.Pros:Implementation inheritance reduces code size by re-using the base class code as it specializes an existing type. Because inheritance is a compile-time declaration, you and the compiler can understand the operation and detect errors. Interface inheritance can be used to programmatically enforce that a class expose a particular API. Again, the compiler can detect errors, in this case, when a class does not define a necessary method of the API.Cons:For implementation inheritance, because the code implementing a sub-class is spread between the base and the sub-class, it can be more difficult to understand an implementation. The sub-class cannot override functions that are not virtual, so the sub-class cannot change implementation. The base class may also define some data members, so that specifies physical layout of the base class.Decision:All inheritance should be public. If you want to do private inheritance, you should be including an instance of the base class as a member instead.Do not overuse implementation inheritance. Composition is often more appropriate. Try to restrict use of inheritance to the "is-a" case: Bar subclasses Foo if it can reasonably be said that Bar"is a kind of" Foo.Make your destructor virtual if necessary. If your class has virtual methods, its destructor should be virtual.Limit the use of protected to those member functions that might need to be accessed from subclasses. Note that data members should be private.When redefining an inherited virtual function, explicitly declare it virtual in the declaration of the derived class. Rationale: If virtual is omitted, the reader has to check all ancestors of the class in question to determine if the function is virtual or not.Multiple InheritanceOnly very rarely is multiple implementation inheritance actually useful. We allow multiple inheritance only when at most one of the base classes has an implementation; all other base classes must be pure interface classes tagged with the Interface suffix.Definition:Multiple inheritance allows a sub-class to have more than one base class. We distinguish between base classes that are pure interfaces and those that havean implementation.Pros:Multiple implementation inheritance may let you re-use even more code than single inheritance (see Inheritance).Cons:Only very rarely is multiple implementation inheritance actually useful. When multiple implementation inheritance seems like the solution, you can usually find a different, more explicit, and cleaner solution.Decision:Multiple inheritance is allowed only when all superclasses, with the possible exception of the first one, are pure interfaces. In order to ensure that they remain pure interfaces, they must end with the Interface suffix.Note: There is an exception to this rule on Windows.Interfaces•It has only public pure virtual ("= 0") methods and static methods (butsee below for destructor).•It may not have non-static data members.•It need not have any constructors defined. If a constructor is provided,it must take no arguments and it must be protected.•If it is a subclass, it may only be derived from classes that satisfythese conditions and are tagged with the Interface suffix.An interface class can never be directly instantiated because of the pure virtual method(s) it declares. To make sure all implementations of the interface can be destroyed correctly, they must also declare a virtual destructor (in an exception to the first rule, this should not be pure). See Stroustrup, The C++ Programming Language, 3rd edition, section 12.4 for details.Pros:Tagging a class with the Interface suffix lets others know that they must not add implemented methods or non static data members. This is particularly important in the caseof multiple inheritance. Additionally, the interface concept is already well-understood by Java programmers.Cons:The Interface suffix lengthens the class name, which can make it harder to read and understand. Also, the interface property may be considered an implementation detail that shouldn't be exposed to clients.Decision:A class may end with Interface only if it meets the above requirements. We do not require the converse, however: classes that meet the above requirements are not required to end with Interface.Operator Overloading•It can fool our intuition into thinking that expensive operations arecheap, built-in operations.•It is much harder to find the call sites for overloaded operators.Searching for Equals() is much easier than searching for relevantinvocations of ==.•Some operators work on pointers too, making it easy to introducebugs. Foo + 4 may do one thing, while &Foo + 4does somethingtotally different. The compiler does not complain for either of these,making this very hard to debug.Overloading also has surprising ramifications. For instance, if a class overloadsunary operator&, it cannot safely be forward-declared.Decision:In general, do not overload operators. The assignment operator (operator=), in particular, is insidious and should be avoided. You can define functions like Equals() and CopyFrom() if you need them. Likewise, avoid the dangerous unary operator& at all costs, if there's any possibility the class might be forward-declared.However, there may be rare cases where you need to overload an operator to interoperate with templates or "standard" C++ classes (such as operator<<(ostream&, const T&) for logging). These are acceptable if fully justified, but you should try to avoid these whenever possible. In particular, do not overload operator== or operator< just so that your class can be used as a key in an STL container; instead, you should create equality and comparison functor types when declaring the container.Some of the STL algorithms do require you to overload operator==, and you may do so in these cases, provided you document why.See also Copy Constructors and Function Overloading.Access ControlDeclaration Order•Typedefs and Enums•Constants (static const data members)•Constructors•Destructor•Methods, including static methods•Data Members (except static const data members)Friend declarations should always be in the private section, andthe DISALLOW_COPY_AND_ASSIGN macro invocation should be at the end ofthe private: section. It should be the last thing in the class. See Copy Constructors. Method definitions in the corresponding .cc file should be the same as the declaration order, as much as possible.Do not put large method definitions inline in the class definition. Usually, only trivial or performance-critical, and very short, methods may be defined inline. See Inline Functions for more details.Write Short FunctionsGoogle-Specific MagicThere are various tricks and utilities that we use to make C++ code more robust, and various ways we use C++ that may differ from what you see elsewhere.Smart PointerscpplintOther C++ Features Reference ArgumentsDefinition:In C, if a function needs to modify a variable, the parameter must use a pointer,eg int foo(int *pval). In C++, the function can alternatively declare a reference parameter: int foo(int &val).Pros:Defining a parameter as reference avoids ugly code like(*pval)++. Necessary for some applications like copy constructors. Makes it clear, unlike with pointers, that NULL is not a possible value.Cons:References can be confusing, as they have value syntax but pointer semantics. Decision:Within function parameter lists all references must be const:In fact it is a very strong convention in Google code that input arguments are valuesor const references while output arguments are pointers. Input parameters maybe const pointers, but we never allow non-const reference parameters.One case when you might want an input parameter to be a const pointer is if you want to emphasize that the argument is not copied, so it must exist for the lifetime of the object; it is usually best to document this in comments as well. STL adapters suchas bind2nd and mem_fun do not permit reference parameters, so you must declare functions with pointer parameters in these cases, too.Function OverloadingPros:Overloading can make code more intuitive by allowing an identically-named function to take different arguments. It may be necessary for templatized code, and it can be convenient for Visitors.Cons:If a function is overloaded by the argument types alone, a reader may have to understand C++'s complex matching rules in order to tell what's going on. Also many people are confused by the semantics of inheritance if a derived class overrides only some of the variants of a function.Decision:If you want to overload a function, consider qualifying the name with some information about the arguments, e.g., AppendString(),AppendInt() rather thanjust Append().Default ArgumentsVariable-Length Arrays and alloca()FriendsExceptions•Exceptions allow higher levels of an application to decide how to handle "can't happen" failures in deeply nested functions, without theobscuring and error-prone bookkeeping of error codes.•Exceptions are used by most other modern languages. Using them in C++ would make it more consistent with Python, Java, and the C++that others are familiar with.•Some third-party C++ libraries use exceptions, and turning them offinternally makes it harder to integrate with those libraries.•Exceptions are the only way for a constructor to fail. We can simulatethis with a factory function or an Init()method, but these requireheap allocation or a new "invalid" state, respectively.•Exceptions are really handy in testing frameworks.Cons:•When you add a throw statement to an existing function, you mustexamine all of its transitive callers. Either they must make at least thebasic exception safety guarantee, or they must never catch theexception and be happy with the program terminating as a result. Forinstance, if f() calls g() calls h(), and h throws an exceptionthat f catches, g has to be careful or it may not clean up properly.•More generally, exceptions make the control flow of programsdifficult to evaluate by looking at code: functions may return in placesyou don't expect. This causes maintainability and debuggingdifficulties. You can minimize this cost via some rules on how andwhere exceptions can be used, but at the cost of more that adeveloper needs to know and understand.•Exception safety requires both RAII and different coding practices.Lots of supporting machinery is needed to make writing correctexception-safe code easy. Further, to avoid requiring readers tounderstand the entire call graph, exception-safe code must isolatelogic that writes to persistent state into a "commit" phase. This willhave both benefits and costs (perhaps where you're forced toobfuscate code to isolate the commit). Allowing exceptions wouldforce us to always pay those costs even when they're not worth it.•Turning on exceptions adds data to each binary produced, increasingcompile time (probably slightly) and possibly increasing addressspace pressure.•The availability of exceptions may encourage developers to throwthem when they are not appropriate or recover from them when it'snot safe to do so. For example, invalid user input should not causeexceptions to be thrown. We would need to make the style guideeven longer to document these restrictions!Decision:On their face, the benefits of using exceptions outweigh the costs, especially in new projects. However, for existing code, the introduction of exceptions has implications on all dependent code. If exceptions can be propagated beyond a new project, it also becomes problematic to integrate the new project into existing exception-free code. Because most existing C++ code atGoogle is not prepared to deal with exceptions, it is comparatively difficult to adopt new code that generates exceptions.Given that Google's existing code is not exception-tolerant, the costs of using exceptions are somewhat greater than the costs in a new project. The conversion process would be slow and error-prone. We don't believe that the available alternatives to exceptions, such as error codes and assertions, introduce a significant burden.Our advice against using exceptions is not predicated on philosophical or moral grounds, but practical ones. Because we'd like to use our open-source projects at Google and it's difficult to do so if those projects use exceptions, we need to advise against exceptions in Googleopen-source projects as well. Things would probably be different if we had to do it all over again from scratch.There is an exception to this rule (no pun intended) for Windows code.Run-Time Type Information (RTTI)If the work belongs outside the object and instead in some processing code, consider a double-dispatch solution, such as the Visitor design pattern. This allows a facility outside the object itself to determine the type of class using the built-in type system.If you think you truly cannot use those ideas, you may use RTTI. But think twice about it. :-) Then think twice again. Do not hand-implement an RTTI-like workaround. The arguments against RTTI apply just as much to workarounds like class hierarchies with type tags.Casting•Use static_cast as the equivalent of a C-style cast that doesvalue conversion, or when you need to explicitly up-cast a pointerfrom a class to its superclass.•Use const_cast to remove the const qualifier (see const).•Use reinterpret_cast to do unsafe conversions of pointer typesto and from integer and other pointer types. Use this only if you knowwhat you are doing and you understand the aliasing issues.•Do not use dynamic_cast except in test code. If you need to knowtype information at runtime in this way outside of a unittest, youprobably have a design flaw.StreamsDefinition:Streams are a replacement for printf() and scanf().Pros:With streams, you do not need to know the type of the object you are printing. You do not have problems with format strings not matching the argument list. (Though with gcc, you do not have that problem with printf either.) Streams have automatic constructors and destructors that open and close the relevant files.Cons:Streams make it difficult to do functionality like pread(). Some formatting (particularly the common format string idiom %.*s) is difficult if not impossible to do efficiently using streams without using printf-like hacks. Streams do not support operator reordering(the %1s directive), which is helpful for internationalization.Decision:Do not use streams, except where required by a logging interface. Use printf-like routines instead.There are various pros and cons to using streams, but in this case, as in many other cases, consistency trumps the debate. Do not use streams in your code.Extended DiscussionThere has been debate on this issue, so this explains the reasoning in greater depth. Recall the Only One Way guiding principle: we want to make sure that whenever we do a certain type of I/O, the code looks the same in all those places. Because of this, we do not want to allow users to decide between using streams or using printf plus Read/Write/etc. Instead, we should settle on one or the other. We made an exception for logging because it is a pretty specialized application, and for historical reasons.Proponents of streams have argued that streams are the obvious choice of the two, but the issue is not actually so clear. For every advantage of streams they point out, there is an equivalent disadvantage. The biggest advantage is that you do not need to know the type of the object to be printing. This is a fair point. But, there is a downside: you can easily use the wrong type, and the compiler will not warn you. It is easy to make this kind of mistake without knowing when using streams.The compiler does not generate an error because << has been overloaded. We discourage overloading for just this reason.Some say printf formatting is ugly and hard to read, but streams are often no better. Consider the following two fragments, both with the same typo. Which is easier to discover?。
Google C++编程风格指南(一):头文件
Google C++编程风格指南(一):头文件本指南的目的是通过详细阐述在C++编码时要怎样写、不要怎样写来规避其复杂性。
本指南的另一个观点是C++特性的臃肿。
C++是一门包含大量高级特性的巨型语言,某些情况下,我们会限制甚至禁止使用某些特性使代码简化,避免可能导致的各种问题头文件通常,每一个.cc文件(C++的源文件)都有一个对应的.h文件(头文件),也有一些例外,如单元测试代码和只包含main()的.cc文件。
正确使用头文件可令代码在可读性、文件大小和性能上大为改观。
下面的规则将引导你规避使用头文件时的各种麻烦。
1. #define的保护所有头文件都应该使用#define防止头文件被多重包含(multiple inclusion),命名格式当是:<PROJECT>_<PATH>_<FILE>_H_为保证唯一性,头文件的命名应基于其所在项目源代码树的全路径。
例如,项目foo中的头文件foo/src/bar/baz.h按如下方式保护:#ifndef FOO_BAR_BAZ_H_#define FOO_BAR_BAZ_H_...#endif // FOO_BAR_BAZ_H_2. 头文件依赖使用前置声明(forward declarations)尽量减少.h文件中#include的数量。
当一个头文件被包含的同时也引入了一项新的依赖(dependency),只要该头文件被修改,代码就要重新编译。
如果你的头文件包含了其他头文件,这些头文件的任何改变也将导致那些包含了你的头文件的代码重新编译。
因此,我们宁可尽量少包含头文件,尤其是那些包含在其他头文件中的。
使用前置声明可以显著减少需要包含的头文件数量。
举例说明:头文件中用到类File,但不需要访问File的声明,则头文件中只需前置声明class File;无需#include "file/base/file.h"。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Google C++编程风格指南edisonpeng 整理2009/3/25Preface背景 (3)头文件 (4)作用域 (8)C++类 (13)智能指针和其他C++特性 (20)命名约定 (32)代码注释 (38)格式 (44)规则之例外 (57)背景Google的项目大多使用C++开发。
每一个C++程序员也都知道,C++具有很多强大的语言特性,但这种强大不可避免的导致它的复杂,而复杂性会使得代码更容易出现bug、难于阅读和维护。
本指南的目的是通过详细阐述如何进行C++编码来规避其复杂性,使得代码在有效使用C++语言特性的同时还易于管理。
使代码易于管理的方法之一是增强代码一致性,让别人可以读懂你的代码是很重要的,保持统一编程风格意味着可以轻松根据“模式匹配”规则推断各种符号的含义。
创建通用的、必需的习惯用语和模式可以使代码更加容易理解,在某些情况下改变一些编程风格可能会是好的选择,但我们还是应该遵循一致性原则,尽量不这样去做。
本指南的另一个观点是C++特性的臃肿。
C++是一门包含大量高级特性的巨型语言,某些情况下,我们会限制甚至禁止使用某些特性使代码简化,避免可能导致的各种问题,指南中列举了这类特性,并解释说为什么这些特性是被限制使用的。
注意:本指南并非C++教程,我们假定读者已经对C++非常熟悉。
头文件通常,每一个.cc文件(C++的源文件)都有一个对应的.h文件(头文件),也有一些例外,如单元测试代码和只包含main()的.cc文件。
正确使用头文件可令代码在可读性、文件大小和性能上大为改观。
下面的规则将引导你规避使用头文件时的各种麻烦。
1. #define保护所有头文件都应该使用#define防止头文件被多重包含(multiple inclusion),命名格式为:<PROJECT>_<PATH>_<FILE>_H_为保证唯一性,头文件的命名应基于其所在项目源代码树的全路径。
例如,项目foo中的头文件foo/src/bar/baz.h按如下方式保护:#ifndef FOO_BAR_BAZ_H_#define FOO_BAR_BAZ_H_...#endif // FOO_BAR_BAZ_H_2. 头文件依赖使用前置声明(forward declarations)尽量减少.h文件中#include的数量。
当一个头文件被包含的同时也引入了一项新的依赖(dependency),只要该头文件被修改,代码就要重新编译。
如果你的头文件包含了其他头文件,这些头文件的任何改变也将导致那些包含了你的头文件的代码重新编译。
因此,我们应该尽量少的包含头文件,尤其是那些包含在其他头文件中的。
使用前置声明可以显著减少需要包含的头文件数量。
举例说明:头文件中用到类File,但不需要访问File 的声明,则头文件中只需前置声明class File;无需#include "file/base/file.h"。
在头文件如何做到使用类Foo而无需访问类的定义?1) 将数据成员类型声明为Foo *或Foo &;2) 参数、返回值类型为Foo的函数只是声明(但不定义实现);3) 静态数据成员的类型可以被声明为Foo,因为静态数据成员的定义在类定义之外。
另一方面,如果你的类是Foo的子类,或者含有类型为Foo的非静态数据成员,则必须为之包含头文件。
有时,使用指针成员(pointer members,如果是scoped_ptr更好)替代对象成员(object members)的确更有意义。
然而,这样的做法会降低代码可读性及执行效率。
如果仅仅为了少包含头文件,还是不要这样替代的好。
当然,.cc文件无论如何都需要所使用类的定义部分,自然也就会包含若干头文件。
注:能依赖声明的就不要依赖定义。
3. 内联函数只有当函数只有10行甚至更少时才会将其定义为内联函数(inline function)。
定义(Definition):当函数被声明为内联函数之后,编译器可能会将其内联展开,无需按通常的函数调用机制调用内联函数。
优点:当函数体比较小的时候,内联该函数可以令目标代码更加高效。
对于存取函数(accessor、mutator)以及其他一些比较短的关键执行函数。
缺点:滥用内联将导致程序变慢,内联有可能是目标代码量或增或减,这取决于被内联的函数的大小。
内联较短小的存取函数通常会减少代码量,但内联一个很大的函数(注:如果编译器允许的话)将显著增加代码量。
在现代处理器上,由于更好的利用指令缓存(instruction cache),小巧的代码往往执行更快。
结论:一个比较得当的处理规则是,不要内联超过10行的函数。
对于析构函数应慎重对待,析构函数往往比其表面看起来要长,因为有一些隐式成员和基类析构函数(如果有的话)被调用!另一有用的处理规则:内联那些包含循环或switch语句的函数是得不偿失的,除非在大多数情况下,这些循环或switch语句从不执行。
重要的是,虚函数和递归函数即使被声明为内联的也不一定就是内联函数。
通常,递归函数不应该被声明为内联的(译者注:递归调用堆栈的展开并不像循环那么简单,比如递归层数在编译时可能是未知的,大多数编译器都不支持内联递归函数)。
析构函数内联的主要原因是其定义在类的定义中,为了方便抑或是对其行为给出文档。
4. -inl.h文件复杂的内联函数的定义,应放在后缀名为-inl.h的头文件中。
在头文件中给出内联函数的定义,可令编译器将其在调用处内联展开。
然而,实现代码应完全放到.cc文件中,我们不希望.h文件中出现太多实现代码,除非这样做在可读性和效率上有明显优势。
如果内联函数的定义比较短小、逻辑比较简单,其实现代码可以放在.h文件中。
例如,存取函数的实现理所当然都放在类定义中。
出于实现和调用的方便,较复杂的内联函数也可以放到.h文件中,如果你觉得这样会使头文件显得笨重,还可以将其分离到单独的-inl.h中。
这样即把实现和类定义分离开来,当需要时包含实现所在的-inl.h即可。
-inl.h文件还可用于函数模板的定义,从而使得模板定义可读性增强。
要提醒的一点是,-inl.h和其他头文件一样,也需要#define保护。
5. 函数参数顺序(Function Parameter Ordering)定义函数时,参数顺序为:输入参数在前,输出参数在后。
C/C++函数参数分为输入参数和输出参数两种,有时输入参数也会输出(注:值被修改时)。
输入参数一般传值或常数引用(const references),输出参数或输入/输出参数为非常数指针(non-const pointers)。
对参数排序时,将所有输入参数置于输出参数之前。
不要仅仅因为是新添加的参数,就将其置于最后,而应该依然置于输出参数之前。
这一点并不是必须遵循的规则,输入/输出两用参数(通常是类/结构体变量)混在其中,会使得规则难以遵循。
6. 包含文件的名称及次序将包含次序标准化可增强可读性、避免隐藏依赖(hidden dependencies,注:隐藏依赖主要是指包含的文件编译),次序如下:C库、C++库、其他库的.h、项目内的.h。
项目内头文件应按照项目源代码目录树结构排列,并且避免使用UNIX文件路径.(当前目录)和..(父目录)。
例如,google-awesome-project/src/base/logging.h应像这样被包含:#include "base/logging.h"dir/的主要作用是执行或测试dir2/foo2.h的功能,中包含头文件的次序如下:dir2/foo2.h(优先位置,详情如下)C系统文件C++系统文件其他库头文件本项目内头文件这种排序方式可有效减少隐藏依赖,我们希望每一个头文件独立编译。
最简单的实现方式是将其作为第一个.h文件包含在对应的.cc中。
dir/和dir2/foo2.h通常位于相同目录下(像base/basictypes_和base/basictypes.h),但也可在不同目录下。
相同目录下头文件按字母序是不错的选择。
举例来说,google-awesome-project/src/foo/internal/的包含次序如下:#include "foo/public/fooserver.h" // 优先位置#include <sys/types.h>#include <unistd.h>#include <hash_map>#include <vector>#include "base/basictypes.h"#include "base/commandlineflags.h"#include "foo/public/bar.h"Summary1. 避免多重包含是学编程时最基本的要求;2. 前置声明是为了降低编译依赖,防止修改一个头文件引发多米诺效应;3. 内联函数的合理使用可提高代码执行效率;4. -inl.h可提高代码可读性(一般用不到吧:D);5. 标准化函数参数顺序可以提高可读性和易维护性(对函数参数的堆栈空间有轻微影响,我以前大多是相同类型放在一起);6. 包含文件的名称使用.和..虽然方便却易混乱,使用比较完整的项目路径看上去很清晰、很条理,包含文件的次序除了美观之外,最重要的是可以减少隐藏依赖,使每个头文件在“最需要编译”(对应源文件处:D)的地方编译,有人提出库文件放在最后,这样出错先是项目内的文件,头文件都放在对应源文件的最前面,这一点足以保证内部错误的及时发现了。
作用域1. 命名空间(Namespaces)在.cc文件中,提倡使用不具名的命名空间(unnamed namespaces,注:不具名的命名空间就像不具名的类一样,似乎被介绍的很少:-()。
使用具名命名空间时,其名称可基于项目或路径名称,不要使用using 指示符。
定义:命名空间将全局作用域细分为不同的、具名的作用域,可有效防止全局作用域的命名冲突。
优点:命名空间提供了(可嵌套)命名轴线(name axis,注:将命名分割在不同命名空间内),当然,类也提供了(可嵌套)的命名轴线(注:将命名分割在不同类的作用域内)。
举例来说,两个不同项目的全局作用域都有一个类Foo,这样在编译或运行时造成冲突。
如果每个项目将代码置于不同命名空间中,project1::Foo和project2::Foo作为不同符号自然不会冲突。
缺点:命名空间具有迷惑性,因为它们和类一样提供了额外的(可嵌套的)命名轴线。
在头文件中使用不具名的空间容易违背C++的唯一定义原则(One Definition Rule (ODR))。