Google-C++编程规范(完整)

合集下载

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++编程风格(Google C++ Style Guide)

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的Objective-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++代码规范

不忍之刃********************头文件< Header Files>The #define Guard所有的头文件都应该使用#define等来防止头文件重复包含,宏的格式应该为:<PROJECT>_<PATH>_<FILE>_H_。

头文件依赖当前面的声明已经满足依赖的时候,不要再使用#include当你包含一个头文件的时候,你就引进了一种依赖,这种依赖会导致:一旦被包含的头文件发生改变,你的代码将会被重新编译。

如果你的头文件还包含了其他的头文件,那么这些头文件的任何改变都会导致包含了你的头文件的代码被重新编译。

因此,我们应该最小化包含头文件,特别要注意那些包含了其他头文件的头文件。

通过使用前向声明可以显著地减少需要包含的头文件的数量。

例如,如果你的头文件想使用File类而不要进入声明了File类的文件,这时你的头文件就可以前向声明File类,而替代掉#include "file/base/file.h"。

如何能在头文件中使用File类而不用进入它的定义文件?●我们可以声明Foo *或者Foo &类型的数据成员。

●我们可以声明但并不定义带参和(或)返回Foo类型值得函数。

(一个例外是,如果参数Foo或const Foo&拥有非显式的单参数构造,那么这种情况下就需要全面的定义以支持自动类型转换)。

●我们可以定义Foo类型的静态数据成员。

这是因为静态数据成员是被定义在类定义体之外的。

另一方面,如果你的类是Foo的子类或者有Foo类型的数据成员,那么你就必须包含Foo 的头文件。

这样似乎我们应该使用指针(或者更好的是scoped_ptr,这是一个简单的智能指针,它能够保证在离开作用域后对象被自动释放)。

但无论如何,这样做降低了代码的易读性和程序的运行效率,所以如果目的仅仅是减少头文件包含,那么还是应该避免这种方法的使用。

c 编程规范

c 编程规范

c 编程规范C 编程规范是用来规范 C 语言程序代码风格和编写规范的一系列准则。

遵循 C 编程规范可以提高代码的可读性、可维护性,减少错误和 bug 的发生。

以下是一些常见的 C 编程规范建议:1. 代码缩进:缩进应该使用相同数量的空格符或制表符,一般为 4 个空格或一个制表符。

缩进可以使代码结构更清晰,便于阅读。

2. 命名规范:变量、函数和常量的命名应该具有描述性,能够准确反映其用途和含义。

使用驼峰命名法或下划线命名法是常见的命名风格。

注意避免使用与 C 语言关键字相同的名称。

3. 注释规范:代码中应该包含必要的注释,用于解释代码的逻辑、实现细节和算法。

注释应该清晰明了,不要出现拼写错误或过多的冗余信息。

4. 函数长度:函数的长度应该适中,不要过长。

一般来说,一个函数应该只负责一个具体的功能,如果函数过长应该考虑分割成多个子函数。

5. 模块化设计:程序应该使用模块化的设计原则,将功能相似或相关的代码块组织成不同的模块或文件。

这样可以提高代码的可维护性和可重用性。

6. 错误处理:程序应该正确处理各种可能发生的错误和异常情况。

避免简单地使用错误代码或忽略错误,而是采取适当的错误处理措施,例如返回错误码或抛出异常。

7. 变量声明:变量应该在使用前先声明,并且尽量在被使用的代码块的起始处进行声明。

声明时应给予适当的初始值,以避免使用未初始化的变量。

8. 代码复用:避免重复的代码和冗余的逻辑。

可以通过编写可重用的函数、使用循环和条件语句等方式来提高代码的复用性和可读性。

9. 括号的使用:括号的使用是保证代码逻辑准确性的重要方式之一。

建议在 if、for、while、switch 等语句块的使用中,使用括号来明确代码块的范围,以避免出现逻辑错误。

10. 代码格式:代码应该有一致的格式,用以增加可读性。

应避免使用过长的代码行,一般建议每行代码长度不超过 80 个字符。

综上所述,C 编程规范是编写高质量、可维护代码的基本准则。

google c++常用命名规则

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++开发代码风格规范,和许多其他公司出的规范⼀样,这份规范规定了⼤量应该做什么,不应该做什么的问题,摘抄⼏个个⼈认为⽐较有意思的⼏个⽅⾯:1、尽量避免异常的编写,这个恐怕是很多学现代语⾔的⼈所很不能够忍受的,尤其是从java那边过来的,或者是C++中编写异常安全代码的⼈所不能够接受的,上⾯的规范也仔细的提及了赞同的与不赞同的观点。

正如C++的产⽣是由其历史原因的,兼容C的代码以及与C类似的风格,导致很多⽤C++的第三⽅库不⼀定都使⽤了异常,这就导致了异常的检查会变得⾮常⿇烦,Google考虑到了更多第三⽅兼容的原因,要求在代码中尽可能避免异常编写。

2、RTTI的使⽤,异常都已经被尽可能的移出了,RTTI也就⾃然被禁⽤了。

3、实现⽂件的命名,很有意思,⽤.cc来命名,不是常见的cpp,没看出来有什么好处!?4、内联函数放置在-inl.h中,这个⽐直接在.h⽂件中要清楚⼀些,通过⽂件名就可以区分是普通的头⽂件还是内联函数⽂件。

5、Google提供了⼀个⽤来检查符合这个规范的python程序⽂件。

Google还是很喜欢Python的风格的。

6、避免匈⽛利命名法,这个可能很难在windows平台上经常性开发MFC程序的⼈接受了。

7、对于LPCTSTR的说法,是显⽰的描述⽐那个隐含的描述要好⼀些,于是要求尽可能使⽤const TCHAR* 来定义8、对于参数引⽤,要求必定是const类型,这个很有必要,虽然引⽤也可以传出值,但是在调⽤⽅,并不能够从代码中⼀眼就可以很清楚的看出,这个引⽤是可能返回值的,也极其容易导致代码中风格规范的不⼀致,⽤指针来表⽰传出值,相对就会更加明显⼀点,如果两者结合起来,就很容易明⽩什么样的参数是传递进去的,什么样的参数可能会有传出值。

其他的规范,在其他公司出的命名规范或者代码风格规范中,也是有类似或者相同的说法,就不列出来了,想要看的,直接去当然,google的东西也不全是ok的,是好是⾮,⾃个⼉取舍,关键是⾃⼰有⼀个稳定的代码风格。

Google计算机C++编码规范中文版

Google计算机C++编码规范中文版
缺点:滥用内联将导致程序发慢,内联有可能是目标代码量戒增戒减,返叏决亍被内联的函数的大小。内 联轳短小的存叏函数通常会减少代码量,但内联一个徆大的函数(注:如果编译器允许的话)将显著增加 代码量。在现代处理器上,由亍更好的利用挃令缓存(instruction cache),小巧的代码往往执行更快。
结论:一个比轳得当的处理觃则是,丌要内联超过 10 行的函数。对亍枂极函数应慎重对待,枂极函数往 往比其表面看起来要长,因为有一些隐式成员和基类枂极函数(如果有的话)被调用!
使代码易亍管理的方法乊一是增强代码一致性,让别人可以诺懂你的代码是徆重要的,保持统一编程风格 意味着可以轱松根据“模式匹配”觃则推断各种符号的吨义。创建通用的、必需的习惯用诧和模式可以使 代码更加容易理解,在某些情冴下改发一些编程风格可能会是好的选择,但我们迓是应该遵循一致性原则, 尽量丌返样去做。
在头文件如何做到使用类 Foo 而无需访问类的定义? 1) 将数据成员类型声明为 Foo *戒 Foo &; 2) 参数、迒回值类型为 Foo 的函数叧是声明(但丌定义实现); 3) 静态数据成员的类型可以被声明为 Foo,因为静态数据成员的定义在类定义乊外。 另一方面,如果你的类是 Foo 的子类,戒者吨有类型为 Foo 的非静态数据成员,则必须为乊包吨头文件。
另一有用的处理觃则:内联那些包吨循环戒 switch 诧句的函数是得丌偿失的,除非在大多数情冴下,返些 循环戒 switch 诧句从丌执行。
重要的是,虚函数和递归函数即使被声明为内联的也丌一定就是内联函数。通常,递归函数丌应该被声明 为内联的(译者注:递归调用堆栈的展开幵丌像循环那么简单,比如递归局数在编译时可能是未知的,大 多数编译器都丌支持内联递归函数)。枂极函数内联的主要原因是其定义在类的定义中,为了方便抑戒是对 其行为给出文档。

Google的C++编程规范

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++编程风格(高清版)

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 C++ 编码规范

Google C++ 编码规范

Important NoteDisplaying Hidden Details in this Guidelink▽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.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. 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 Guardlink▽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:Header 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 minimize the number of header files you need to include in your own header files by using forward declarations. For example, if your header file usesthe 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/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 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- andbase-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 Fileslink▽You 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 thatcode 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 Orderinglink▽When 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 (oftenclasses/structs) muddy the waters, and, as always, consistency with related functions may require you to bend the rule.Names and Order of Includeslink▽Use 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 descentants of the project's source directory without use of UNIX directory shortcuts . (the current directory) or .. (the parent directory). For example, google-awesome-project/src/base/logging.h should be included asIn 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:ScopingNamespaceslink▽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.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 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.∙Do not declare anything in namespace std, not even forward declarations of standard library classes. Declaring entities innamespace std is undefined behavior, i.e., not portable. To declare entities from the standard library, include the appropriate header file.Note that an alias in a .h file is visible to everyone #including that file,so public headers (those available outside a project) and headerstransitively #included by them, should avoid defining aliases, as partof 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, considera namespace to keep declarations out of the global scope.Definition:A class can define another class within it; this is also called a member class.Pros: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 Functionslink▽Prefer 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 anamespace. 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 Variableslink▽Place 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 initialized to. In particular, initialization should be used instead of declaration and assignment, e.g.Note 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 Variableslink▽Static 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 theorder-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 Constructorslink▽In 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 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 Constructorslink▽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.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 Constructorslink▽Use 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 passthe 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 Constructorslink▽Provide 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, suchas 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).For convenience, a DISALLOW_COPY_AND_ASSIGN macro can be used:Then, in class Foo:Structs vs. Classeslink▽Use 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 thedata-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.Inheritancelink▽Composition 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 changeimplementation. 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 Inheritancelink▽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.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.。

google公开的c++编程规范

google公开的c++编程规范
link
▽ 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.

GoogleC编程规范

GoogleC编程规范

GoogleC编程规范一、头文件1. #define 的保护2. 头文件依赖3. 内联函数4. -inl.h 文件5. 函数参数顺序(Function Parameter Ordering)6. 包含文件的名称及次序二、作用域1. 命名空间(Namespaces)2. 嵌套类(Nested Class)3. 非成员函数(Nonmember)、静态成员函数(Static Member)和全局函数(Global Functions)4. 局部变量(Local Variables)5. 全局变量(Global Variables)三、类1. 构造函数(Constructor)的职责2. 默认构造函数(Default Constructors)3. 明确的构造函数(Explicit Constructors)4. 拷贝构造函数(Copy Constructors)5. 结构体和类(Structs vs. Classes)6. 继承(Inheritance)7. 多重继承(Multiple Inheritance)8. 接口(Interface)9. 操作符重载(Operator Overloading)10. 存取控制(Access Control)11. 声明次序(Declaration Order)12. 编写短小函数(Write Short Functions)四、Google 特有的风情1. 智能指针(Smart Pointers)五、其他C++特性1. 引用参数(Reference Arguments)2. 函数重载(Function Overloading)3. 缺省参数(Default Arguments)4. 变长数组和alloca(Variable-Length Arrays and alloca())5. 友元(Friends)6. 异常(Exceptions)7. 运行时类型识别(Run-Time Type Information, RTTI)8. 类型转换(Casting)9. 流(Streams)10. 前置自增和自减(Preincrement and Predecrement)11. const 的使用(Use of const)12. 整型(Integer Types)13. 64 位下的可移植性(64-bit Portability)14. 预处理宏(Preprocessor Macros)15. 0 和 NULL(0 and NULL)16. sizeof(sizeof)17. Boost 库(Boost)六、命名约定1. 通用命名规则(General Naming Rules)2. 文件命名(File Names)3. 类型命名(Type Names)4. 变量命名(Variable Names)5. 常量命名(Constant Names)6. 函数命名(Function Names)7. 命名空间(Namespace Names)8. 枚举命名(Enumerator Names)9. 宏命名(Macro Names)10. 命名规则例外(Exceptions to Naming Rules)七、注释1. 注释风格(Comment Style)2. 文件注释(File Comments)3. 类注释(Class Comments)4. 函数注释(Function Comments)5. 变量注释(Variable Comments)6. 实现注释(Implementation Comments)7. 标点、拼写和语法(Punctuation, Spelling and Grammar)8. TODO 注释(TODO Comments)八、格式1. 行长度(Line Length)2. 非 ASCII 字符(Non-ASCII Characters)3. 空格还是制表位(Spaces vs. Tabs)4. 函数声明与定义(Function Declarations and Definitions)5. 函数调用(Function Calls)6. 条件语句(Conditionals)7. 循环和开关选择语句(Loops and Switch Statements)8. 指针和引用表达式(Pointers and Reference Expressions)9. 布尔表达式(Boolean Expressions)10. 函数返回值(Return Values)11. 变量及数组初始化(Variable and Array Initialization)12. 预处理指令(Preprocessor Directives)13. 类格式(Class Format)14. 初始化列表(Initializer Lists)15. 命名空间格式化(Namespace Formatting)16. 水平留白(Horizontal Whitespace)17. 垂直留白(Vertical Whitespace)九、规则之例外1. 现有不统一代码(Existing Non-conformant Code)2. Windows 代码(Windows Code)十、团队合作一、头文件通常,每一个.cc 文件(C++的源文件)都有一个对应的.h 文件(头文件),也有一些例外,如单元测试代码和只包含main()的.cc 文件。

Google的C++代码规范

Google的C++代码规范

Google的C++代码规范英⽂版:中⽂版:google c++ 编码规范:⽹上有电⼦版 PDF ,可以下载看下。

(电⼦版下载地址:)Google C++ 编码规范很早就已经公开了,李开复也在其微博上公开分享:”我认为这是地球上最好的⼀份C++编程规范,没有之⼀,建议⼴⼤国内外IT研究使⽤。

“Google C++ Style Guide是⼀份不错的C++编码指南,下⾯是⼀张⽐较全⾯的说明图,可以在短时间内快速掌握规范的重点内容。

不过规范毕竟是⼈定的,记得活学活⽤。

1. 保持⼀致也⾮常重要,如果你在⼀个⽂件中新加的代码和原有代码风格相去甚远的话,这就破坏了⽂件本⾝的整体美观也影响阅读,所以要尽量避免。

2. ⼀些条⽬往往有例外,⽐如下⾯这些,所以本图不能代替⽂档,有时间还是把PDF认真阅读⼀遍吧。

异常在测试框架中确实很好⽤RTTI在某些单元测试中⾮常有⽤在记录⽇志时可以使⽤流操作符重载不提倡使⽤,有些STL 算法确实需要重载operator==时可以这么做。

注:原图较⼤,在新标签页中打开或保存到本地打开更清晰头⽂件 函数参数顺序 C/C++函数参数分为输⼊参数和输出参数两种,有时输⼊参数也会输出(注:值被修改时)。

输⼊参数⼀般传值或常数引⽤(const references),输出参数戒输⼊/输出参数为⾮常数指针(non-const pointers)。

对参数排序时,将所有输⼊参数置于输出参数之前。

不要仅仅因为是新添加的参数,就将其置于最后,⽽应该依然置于输出参数之前。

这⼀点并不是必须遵循的规则,输⼊/输出两⽤参数(通常是类/结构体变量)混在其中,会使得规则难以遵守。

个⼈感受:这条规则相当重要,⾃⼰写代码的时候可能没有太⼤感觉,但是在阅读别⼈代码的时候感觉特别明显。

如果代码按照这种规范来写,从某种⾓度来说,这段代码具有“⾃注释”的功能,那么在看代码的时候就会⽐较轻松。

Doom3的代码规范中提到,“Use ‘const’ as much as possible”,也是同样的意义。

Google C++编程风格指南(一):头文件

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"。

Google的C++编码规范

Google的C++编码规范

Google C++ Style GuideRevision 3.180Benjy WeinbergerCraig SilversteinGregory EitzmannMark MentovaiTashana Landray Each 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 ContentsImportant 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'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 files containing just a main() function.Correct use of header files can make a huge difference to the readability, size and performanceof 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▶Don't use an #include when a forward declaration would suffice.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, considera 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.Static and Global Variables▶Static or global variables of class type are forbidden: they cause hard-to-find bugs due to indeterminate order of construction and destruction.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▶In general, constructors should merely set member variables to their initial values. Any complex initialization should go in an explicit Init() method.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▶Provide a copy constructor and assignment operator only when necessary. Otherwise, disable them with 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 withan Interface suffix.Operator Overloading▶Do not overload operators except in rare, special circumstances.Access Control▶Make data members private, and provide access to them through accessor functions as needed (for technical reasons, we allow data members of a test fixture class tobe protected when using Google Test). Typically a variable would be called foo_ and the accessor function foo(). You may also want a mutator function set_foo(). Exception: static const data members (typically called kFoo) need not be private.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 onlyuse 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.cpplint▶Use cpplint.py to detect style errors.Other C++ FeaturesReference Arguments▶All parameters passed by reference must be labeled const.Function Overloading▶Use overloaded functions (including constructors) only if a reader looking at a call site can get a good idea of what is happening without having to first figure out exactly which overload is being called.Default Arguments▶We do not allow default function parameters, except in a few uncommon situations explained below.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.C++0x▶Use only approved libraries and language extensions from C++0x. Currently, none are approved.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. If there is no consistent local pattern to follow, prefer "_".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. Forinstance: 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 thevariable: MyExcitingFunction(),MyExcitingMethod(), my_exciting_member_variab le(), 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 NamesMacro Names▶You're not really going to define a macro, are you? If you do, they're likethis: 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 is self-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 read well-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.Deprecation Comments▶Mark deprecated interface points with DEPRECATED comments.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.To help you format code correctly, we've created a settings file for emacs.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 needlessly 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.Constructor 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 foranyone 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!Revision 3.180Benjy WeinbergerCraig SilversteinGregory EitzmannMark MentovaiTashana Landray。

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_为保证唯一性,头文件的命名应基于其所在项目源代码树的全路径。

例如,项目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的数量。

google c++常用命名规则

google c++常用命名规则

google c++常用命名规则C++是一种广泛使用的编程语言,命名规则对于编写清晰、易读、易维护的代码非常重要。

在C++中,有一些普遍适用的命名规则,包括标识符命名、常量命名、类命名、函数命名和文件命名等。

本文将详细介绍这些常用的C++命名规则。

一、标识符命名在C++中,标识符是用来命名变量、函数、类、结构体等的名称。

以下是一些标识符命名的常规规则:1.标识符应以字母或下划线(_)开头,不能以数字开头。

2.标识符可以包含字母、数字和下划线。

3.标识符对大小写敏感,例如Name和name是不同的标识符。

4.使用有意义的名称,能够反映标识符的含义和用途。

5.避免使用C++的关键字作为标识符,例如int、class、if等。

6.使用驼峰命名法(Camel Case)或下划线命名法(Underscore Case)来命名标识符。

驼峰命名法是一种常用的命名规则,有两种变体:大驼峰命名法和小驼峰命名法。

大驼峰命名法将每个单词的首字母都大写,例如MyVariable。

小驼峰命名法将第一个单词的首字母小写,其他单词的首字母大写,例如myVariable。

下划线命名法将单词使用下划线分隔,例如my_variable。

这种命名法在C++中较为常见,特别是在一些库、框架和代码风格中。

二、常量命名与标识符命名类似,常量命名也应具有一定的规范。

以下是一些常量命名的常规规则:1.常量名应全部大写,单词之间使用下划线分隔,例如MAX_VALUE。

2.使用有意义的常量名,能够清晰地表达常量的含义和作用。

3.如果常量是某个类的静态成员,可以使用类名作为前缀,例如MyClass::CONSTANT_VALUE。

4.避免使用单个字符或无意义的常量名,例如x、a、b等。

三、类命名在C++中,类是一种重要的编程结构,良好的类命名能够提高代码的可读性。

以下是一些类命名的常规规则:1.类名使用大驼峰命名法,以便与变量和函数命名进行区分。

2.使用清晰、准确和具有描述性的名称,能够清楚地表达类的特点和功能。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

•背景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_为保证唯一性,头文件的命名应基于其所在项目源代码树的全路径。

例如,项目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"______________________________________译者:英语不太好,翻译的也就不太好。

这一篇主要提到的是头文件的一些规则,总结一下:1. 避免多重包含是学编程时最基本的要求;2. 前置声明是为了降低编译依赖,防止修改一个头文件引发多米诺效应;3. 内联函数的合理使用可提高代码执行效率;4. -inl.h可提高代码可读性(一般用不到吧:D);5. 标准化函数参数顺序可以提高可读性和易维护性(对函数参数的堆栈空间有轻微影响,我以前大多是相同类型放在一起);6. 包含文件的名称使用.和..虽然方便却易混乱,使用比较完整的项目路径看上去很清晰、很条理,包含文件的次序除了美观之外,最重要的是可以减少隐藏依赖,使每个头文件在“最需要编译”(对应源文件处:D)的地方编译,有人提出库文件放在最后,这样出错先是项目内的文件,头文件都放在对应源文件的最前面,这一点足以保证内部错误的及时发现了。

•作用域1. 命名空间(Namespaces)在.cc文件中,提倡使用不具名的命名空间(unnamed namespaces,译者注:不具名的命名空间就像不具名的类一样,似乎被介绍的很少:-()。

使用具名命名空间时,其名称可基于项目或路径名称,不要使用using指示符。

定义:命名空间将全局作用域细分为不同的、具名的作用域,可有效防止全局作用域的命名冲突。

优点:命名空间提供了(可嵌套)命名轴线(name axis,译者注:将命名分割在不同命名空间内),当然,类也提供了(可嵌套)的命名轴线(译者注:将命名分割在不同类的作用域内)。

举例来说,两个不同项目的全局作用域都有一个类Foo,这样在编译或运行时造成冲突。

如果每个项目将代码置于不同命名空间中,project1::Foo和project2::Foo作为不同符号自然不会冲突。

相关文档
最新文档