google编程规范
- 格式:docx
- 大小:37.17 KB
- 文档页数:2
Google C++编程风格指南edisonpeng 整理2009/3/25目录背景 (3)头文件 (4)作用域 (8)类 (13)来自Google 的奇技 (20)其他C++特性 (32)命名约定 (32)注释 (38)格式 (44)规则特例 (57)背景C++ 是Google 大部分开源项目的主要编程语言. 正如每个C++ 程序员都知道的, C++ 有很多强大的特性, 但这种强大不可避免的导致它走向复杂,使代码更容易产生bug, 难以阅读和维护.本指南的目的是通过详细阐述C++ 注意事项来驾驭其复杂性. 这些规则在保证代码易于管理的同时, 高效使用C++ 的语言特性.风格, 亦被称作可读性, 也就是指导C++ 编程的约定. 使用术语―风格‖ 有些用词不当, 因为这些习惯远不止源代码文件格式化这么简单.使代码易于管理的方法之一是加强代码一致性. 让任何程序员都可以快速读懂你的代码这点非常重要. 保持统一编程风格并遵守约定意味着可以很容易根据―模式匹配‖ 规则来推断各种标识符的含义. 创建通用, 必需的习惯用语和模式可以使代码更容易理解. 在一些情况下可能有充分的理由改变某些编程风格, 但我们还是应该遵循一致性原则,尽量不这么做. 本指南的另一个观点是C++ 特性的臃肿. C++ 是一门包含大量高级特性的庞大语言. 某些情况下, 我们会限制甚至禁止使用某些特性. 这么做是为了保持代码清爽, 避免这些特性可能导致的各种问题. 指南中列举了这类特性, 并解释为什么这些特性被限制使用.Google 主导的开源项目均符合本指南的规定.注意: 本指南并非C++ 教程, 我们假定读者已经对C++ 非常熟悉.1、头文件通常每一个.cc文件都有一个对应的.h文件. 也有一些常见例外, 如单元测试代码和只包含main()函数的.cc文件.正确使用头文件可令代码在可读性、文件大小和性能上大为改观.下面的规则将引导你规避使用头文件时的各种陷阱.1.1. #define 保护Tip所有头文件都应该使用#define防止头文件被多重包含, 命名格式当是: <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_1.2. 头文件依赖Tip能用前置声明的地方尽量不使用#include.当一个头文件被包含的同时也引入了新的依赖, 一旦该头文件被修改, 代码就会被重新编译. 如果这个头文件又包含了其他头文件, 这些头文件的任何改变都将导致所有包含了该头文件的代码被重新编译. 因此, 我们倾向于减少包含头文件, 尤其是在头文件中包含头文件.使用前置声明可以显著减少需要包含的头文件数量. 举例说明: 如果头文件中用到类File, 但不需要访问File类的声明, 头文件中只需前置声明class File;而无须#include "file/base/file.h".不允许访问类的定义的前提下, 我们在一个头文件中能对类Foo做哪些操作?∙我们可以将数据成员类型声明为Foo *或Foo &.∙我们可以将函数参数/ 返回值的类型声明为Foo (但不能定义实现).∙我们可以将静态数据成员的类型声明为Foo, 因为静态数据成员的定义在类定义之外.反之, 如果你的类是Foo的子类, 或者含有类型为Foo的非静态数据成员, 则必须包含Foo所在的头文件.有时, 使用指针成员(如果是scoped_ptr更好) 替代对象成员的确是明智之选. 然而, 这会降低代码可读性及执行效率, 因此如果仅仅为了少包含头文件,还是不要这么做的好.当然.cc文件无论如何都需要所使用类的定义部分, 自然也就会包含若干头文件.1.3. 内联函数Tip只有当函数只有10 行甚至更少时才将其定义为内联函数.定义:当函数被声明为内联函数之后, 编译器会将其内联展开, 而不是按通常的函数调用机制进行调用.优点:当函数体比较小的时候, 内联该函数可以令目标代码更加高效. 对于存取函数以及其它函数体比较短, 性能关键的函数, 鼓励使用内联.缺点:滥用内联将导致程序变慢. 内联可能使目标代码量或增或减, 这取决于内联函数的大小. 内联非常短小的存取函数通常会减少代码大小, 但内联一个相当大的函数将戏剧性的增加代码大小. 现代处理器由于更好的利用了指令缓存, 小巧的代码往往执行更快。
Google代码规范⼯具Cpplint的使⽤Cpplint是⼀个python脚本,Google使⽤它作为⾃⼰的C++代码规范检查⼯具。
假设你所在的公司也使⽤Google C++代码规范,那么你有必要了解下Cpplint。
以下说⼀下Cpplint在windows下的简单使⽤:1. 从源代码。
并将其存放到D:\soft\Cpplint\cpplint.py中;2. 从下载python-2.7.10.msi;3. 安装python,并将D:\ProgramFiles\Python27 加⼊到系统环境变量Path中;4. 写⼀个測试⽂件E:/tmp/test.cpp。
内容例如以下:#include <iostream>using namespace std;int main(){cout<<"hello !"<<endl;return 0;}5. 打开命令提⽰符,例如以下,会发现⼀共同拥有9个错误:6. 依照错误提⽰,对test.cpp⽂件进⾏改动,改动后的⽂件为test1.cpp。
内容例如以下:/*# Copyright (c) 2015 Bingchun Feng. All rights reserved.*/#include <iostream>int main() {std::cout << "hello !" << std::endl;return 0;}7. 运⾏。
例如以下。
发现所有错误所有清理掉了:8. cpplint.py默认⽀持的⽂件格式包含(见cpplint.py⽂件第502⾏):.cc、.h、.cpp、.cu、.cuh,默认不⽀持.hpp⽂件,如test3.hpp,运⾏会报错:/*# Copyright (c) 2015 Bingchun Feng. All rights reserved.*/#ifndef CPP_LINT_TEST_HPP_#define CPP_LINT_TEST_HPP_class A {public:int add(int a, int b);int mul(int a, int b);private:int m_a, m_b;}#endif // CPP_LINT_TEST_HPP_9. 将cpplint.py⽂件第502⾏后改为以下就可以⽀持.hpp⽂件:_valid_extensions = set([‘cc’, ‘h’, ‘cpp’, ‘cu’, ‘cuh’, ‘hpp’])10. 其他相关选项说明:(1)、对于发现的每⼀个问题,cpplint都会给出⼀个位于区间[1, 5]之间的置信度评分,分数越⾼就代表问题越肯定,能够通过verbose选项控制输出哪些级别。
不忍之刃********************头文件< 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,这是一个简单的智能指针,它能够保证在离开作用域后对象被自动释放)。
但无论如何,这样做降低了代码的易读性和程序的运行效率,所以如果目的仅仅是减少头文件包含,那么还是应该避免这种方法的使用。
分号行长度括号foo_bar(self, width, height, color='black', design=None, x='foo',emphasis=None, highlight=0)if (width == 0 and height == 0 andcolor == 'red' and emphasis == 'strong'):x = ('这是一个非常长非常长非常长非常长 ''非常长非常长非常长非常长非常长非常长的字符串')# See details at# /us/developer/documentation/api/content/v2.0/csv_file_name_exte nsion_full_specification.html# See details at# /us/developer/documentation/api/content/\# v2.0/csv_file_name_extension_full_specification.html宁缺毋滥的使用括号除非是用于实现行连接, 否则不要在返回语句或条件语句中使用括号. 不过在元组两边使用括号是可以的.Yes:No:缩进用4个空格来缩进代码绝对不要用tab, 也不要tab 和空格混用. 对于行连接的情况, 你应该要么垂直对齐换行的元素(见 :ref:`行长度 <line_len gth>` 部分的示例), 或者使用4空格的悬挂式缩进(这时第一行不应该有参数):if foo: bar()while x: x = bar()if x and y: bar()if not x: bar()return foo for (x, y) in dict.items(): ...if (x): bar()if not(x): bar()return (foo)Yes: # 与起始变量对齐 foo = long_function_name(var_one, var_two, var_three, var_four)# 字典中与起始值对齐 foo = { long_dictionary_key: value1 + value2, ... }# 4 个空格缩进,第一行不需要 foo = long_function_name( var_one, var_two, var_three, var_four)# 字典中 4 个空格缩进 foo = { long_dictionary_key: long_dictionary_value, ... }No: # 第一行有空格是禁止的 foo = long_function_name(var_one, var_two, var_three, var_four)# 2 个空格是禁止的 foo = long_function_name( var_one, var_two, var_three, var_four)# 字典中没有处理缩进 foo = { long_dictionary_key: long_dictionary_value, ... }空行顶级定义之间空两行, 方法定义之间空一行顶级定义之间空两行, 比如函数或者类定义. 方法定义, 类定义与第一个方法之间, 都应该空一行. 函数或方法中, 某些地方要是你觉得合适, 就空一行.空格按照标准的排版规范来使用标点两边的空格括号内不要有空格.按照标准的排版规范来使用标点两边的空格Yes: spam(ham[1], {eggs: 2}, [])No: spam( ham[ 1 ], { eggs: 2 }, [ ] )不要在逗号, 分号, 冒号前面加空格, 但应该在它们后面加(除了在行尾).参数列表, 索引或切片的左括号前不应加空格.Yes: spam(1)no: spam (1)Yes: dict['key'] = list[index]No: dict ['key'] = list [index]在二元操作符两边都加上一个空格, 比如赋值(=), 比较(==, <, >, !=, <>, <=, >=, in, not in, is, is not), 布尔(and, o r, not). 至于算术操作符两边的空格该如何使用, 需要你自己好好判断. 不过两侧务必要保持一致.Yes: x == 1No: x<1当'='用于指示关键字参数或默认参数值时, 不要在其两侧使用空格.Yes: def complex(real, imag=0.0): return magic(r=real, i=imag)No: def complex(real, imag = 0.0): return magic(r = real, i = imag)不要用空格来垂直对齐多行间的标记, 因为这会成为维护的负担(适用于:, #, =等):Yes: if x == 4: print x, y x, y = y, xNo: if x == 4 : print x , y x , y = y , xYes: foo = 1000 # 注释 long_name = 2 # 注释不需要对齐dictionary = { "foo": 1, "long_name": 2, }No: foo = 1000 # 注释 long_name = 2 # 注释不需要对齐dictionary = {Shebang大部分.py 文件不必以#!作为文件的开始. 根据 PEP-394 , 程序的main 文件应该以 #!/usr/bin/python2或者 #!/usr/bin/python3开始.(译者注: 在计算机科学中, Shebang (也称为Hashbang)是一个由井号和叹号构成的字符串行(#!), 其出现在文本文件的第一行的前两个字符. 在文件中存在Shebang 的情况下, 类Unix 操作系统的程序载入器会分析Shebang 后的内容, 将这些内容作为解释器指令, 并调用该指令, 并将载有Shebang 的文件路径作为该解释器的参数. 例如, 以指令#!/bin/sh 开头的文件在执行时会实际调用/bin/sh 程序.)#!先用于帮助内核找到Python 解释器, 但是在导入模块时, 将会被忽略. 因此只有被直接执行的文件中才有必要加入#!.注释确保对模块, 函数, 方法和行内注释使用正确的风格文档字符串Python 有一种独一无二的的注释方式: 使用文档字符串. 文档字符串是包, 模块, 类或函数里的第一个语句. 这些字符串可以通过对象的__doc__成员被自动提取, 并且被pydoc 所用. (你可以在你的模块上运行pydoc 试一把, 看看它长什么样). 我们对文档字符串的惯例是使用三重双引号"""( PEP-257 ). 一个文档字符串应该这样组织: 首先是一行以句号, 问号或惊叹号结尾的概述(或者该文档字符串单纯只有一行). 接着是一个空行. 接着是文档字符串剩下的部分, 它应该与文档字符串的第一行的第一个引号对齐. 下面有更多文档字符串的格式化规范.模块每个文件应该包含一个许可样板. 根据项目使用的许可(例如, Apache 2.0, BSD, LGPL, GPL), 选择合适的样板.函数和方法下文所指的函数,包括函数, 方法, 以及生成器.一个函数必须要有文档字符串, 除非它满足以下条件:1、外部不可见2、非常短小3、简单明了文档字符串应该包含函数做什么, 以及输入和输出的详细描述. 通常, 不应该描述"怎么做", 除非是一些复杂的算法. 文档字符串应该提供足够的信息, 当别人编写代码调用该函数时, 他不需要看一行代码, 只要看文档字符串就可以了. 对于复杂的代码, 在代码旁边加注释会比使用文档字符串更有意义.关于函数的几个方面应该在特定的小节中进行描述记录, 这几个方面如下文所述. 每节应该以一个标题行开始. 标题行以冒号结尾. 除标题行外, 节的其他内容应被缩进2个空格.Args:列出每个参数的名字, 并在名字后使用一个冒号和一个空格, 分隔对该参数的描述.如果描述太长超过了单行80字符,使用2或者4个空格的悬挂缩进(与文件其他部分保持一致). 描述应该包括所需的类型和含义. 如果一个函数接受*foo(可变长度参数列表)或者**bar (任意关键字参数), 应该详细列出*foo 和**bar.Returns: (或者 Yields: 用于生成器)描述返回值的类型和语义. 如果函数返回None, 这一部分可以省略."foo" : 1, "long_name": 2, }Raises:列出与接口有关的所有异常.类类应该在其定义下有一个用于描述该类的文档字符串. 如果你的类有公共属性(Attributes), 那么文档中应该有一个属性(Attributes)段. 并且应该遵守和函数参数相同的格式.块注释和行注释最需要写注释的是代码中那些技巧性的部分. 如果你在下次 代码审查 的时候必须解释一下, 那么你应该现在就给它写注释. 对于复杂的操作, 应该在其操作开始前写上若干行注释. 对于不是一目了然的代码, 应在其行尾添加注释.def fetch_bigtable_rows(big_table, keys, other_silly_variable=None): """Fetches rows from a Bigtable.Retrieves rows pertaining to the given keys from the Table instance represented by big_table. Silly things may happen if other_silly_variable is not None.Args: big_table: An open Bigtable Table instance. keys: A sequence of strings representing the key of each table row to fetch. other_silly_variable: Another optional variable, that has a much longer name than the other args, and which does nothing.Returns: A dict mapping keys to the corresponding table row data fetched. Each row is represented as a tuple of strings. For example:{'Serak': ('Rigel VII', 'Preparer'), 'Zim': ('Irk', 'Invader'), 'Lrrr': ('Omicron Persei 8', 'Emperor')}If a key from the keys argument is missing from the dictionary, then that row was not found in the table.Raises: IOError: An error occurred accessing the bigtable.Table object. """ passclass SampleClass(object): """Summary of class here.Longer class information.... Longer class information....Attributes: likes_spam: A boolean indicating if we like SPAM or not. eggs: An integer count of the eggs we have laid. """def __init__(self, likes_spam=False): """Inits SampleClass with blah.""" self.likes_spam = likes_spam self.eggs = 0def public_method(self): """Performs operation blah."""# We use a weighted dictionary search to find out where i is in # the array. We extrapolate position based on the largest num # in the array and the array size and then do binary search to # get the exact number.if i & (i-1) == 0: # true iff i is a power of 2为了提高可读性, 注释应该至少离开代码2个空格.另一方面, 绝不要描述代码. 假设阅读代码的人比你更懂Python, 他只是不知道你的代码要做什么.# BAD COMMENT: Now go through the b array and make sure whenever i occurs # the next element is i+1类如果一个类不继承自其它类, 就显式的从object 继承. 嵌套类也一样.继承自 object 是为了使属性(properties)正常工作, 并且这样可以保护你的代码, 使其不受Python 3000的一个特殊的潜在不兼容性影响. 这样做也定义了一些特殊的方法, 这些方法实现了对象的默认语义, 包括 __new__, __init__, __de lattr__, __getattribute__, __setattr__, __hash__, __repr__, and __str__ .字符串避免在循环中用+和+=操作符来累加字符串. 由于字符串是不可变的, 这样做会创建不必要的临时对象, 并且导致二次方而不是线性的运行时间. 作为替代方案, 你可以将每个子串加入列表, 然后在循环结束后用 .join 连接列表. (也可以将每个子串写入一个 cStringIO.StringIO 缓存中.)在同一个文件中, 保持使用字符串引号的一致性. 使用单引号'或者双引号"之一用以引用字符串, 并在同一文件中沿用. 在字符串内可以使用另外一种引号, 以避免在字符串中使用. PyLint 已经加入了这一检查.Yes: class SampleClass(object): pass class OuterClass(object): class InnerClass(object): passclass ChildClass(ParentClass): """Explicitly inherits from another class already."""No: class SampleClass: passclass OuterClass: class InnerClass: passYes: x = a + b x = '%s, %s!' % (imperative, expletive) x = '{}, {}!'.format(imperative, expletive) x = 'name: %s; score: %d' % (name, n) x = 'name: {}; score: {}'.format(name, n)No: x = '%s%s' % (a, b) # use + in this case x = '{}{}'.format(a, b) # use + in this case x = imperative + ', ' + expletive + '!' x = 'name: ' + name + '; score: ' + str(n)Yes: items = ['<table>'] for last_name, first_name in employee_list: items.append('<tr><td>%s, %s</td></tr>' % (last_name, first_name)) items.append('</table>') employee_table = ''.join(items)No: employee_table = '<table>' for last_name, first_name in employee_list: employee_table += '<tr><td>%s, %s</td></tr>' % (last_name, first_name) employee_table += '</table>'Yes: Python('Why are you hiding your eyes?') Gollum("I'm scared of lint errors.") Narrator('"Good!" thought a happy Python reviewer.')多行字符串使用三重双引号"""而非三重单引号'''. 当且仅当项目中使用单引号'来引用字符串时, 才可能会使用三重'''文件和socketsLegacy AppEngine 中Python 2.5的代码如使用"with"语句, 需要添加 "from __future__ import with_statement".TODO 注释No: Python("Why are you hiding your eyes?") Gollum('The lint. It burns. It burns us.') Gollum("Always the great lint. Watching. Watching.")Yes: print ("This is much nicer.\n" "Do it this way.\n")No: print """This is pretty ugly. Don't do this. """with open("hello.txt") as hello_file: for line in hello_file: print lineimport contextlibwith contextlib.closing(urllib.urlopen("/")) as front_page: for line in front_page: print line导入格式总应该放在文件顶部, 位于模块注释和文档字符串之后, 模块全局变量和常量之前. 导入应该按照从最通用到最不语句访问控制Yes: import os import sysNo: import os, sysimport foo from foo import bar from foo.bar import baz from foo.bar import Quux from Foob import arYes:if foo: bar(foo)No:if foo: bar(foo) else: baz(foo)try: bar(foo) except ValueError: baz(foo)try: bar(foo) except ValueError: baz(foo)命名Main即使是一个打算被用作脚本的文件, 也应该是可导入的. 并且简单的导入不应该导致这个脚本的主功能(main functiona lity)被执行, 这是一种副作用. 主功能应该放在一个main()函数中.在Python 中, pydoc 以及单元测试要求模块必须是可导入的. 你的代码应该在执行主程序前总是检查 if __name__ == '__main__' , 这样当模块被导入时主程序就不会被执行.所有的顶级代码在模块导入时都会被执行. 要小心不要去调用函数, 创建对象, 或者执行那些不应该在使用pydoc 时执行的操作. def main(): ...if __name__ == '__main__': main()。
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++常用命名规则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.使用清晰、准确和具有描述性的名称,能够清楚地表达类的特点和功能。
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++编程风格指南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_为保证唯一性,头文件的命名应基于其所在项目源代码树的全路径。
R 语言是一门主要用于统计计算和绘图的高级编程语言. 这份R 语言编码风格指南旨在让我们的R 代码更容易阅读、分享和检查. 以下规则系与Google 的R 用户群体协同设计而成.概要: R编码风格约定文件命名: 以.R (大写) 结尾标识符命名: , FunctionName, kConstantName单行长度: 不超过80 个字符缩进: 两个空格, 不使用制表符空白花括号: 前括号不折行写, 后括号独占一行赋值符号: 使用<-, 而非=分号: 不要用总体布局和顺序注释准则: 所有注释以# 开始, 后接一个空格; 行内注释需要在# 前加两个空格函数的定义和调用函数文档示例函数TODO 书写风格: TODO(您的用户名)概要: R语言使用规则attach: 避免使用函数: 错误(error) 应当使用stop() 抛出对象和方法: 尽可能避免使用S4 对象和方法; 永远不要混用S3 和S4表示和命名文件命名文件名应以.R (大写) 结尾, 文件名本身要有意义.正例: predict_ad_revenue.R反例: foo.R标识符命名在标识符中不要使用下划线( _ ) 或连字符( - ). 标识符应根据如下惯例命名. 变量名应使用点(.) 分隔所有的小写字母或单词; 函数名首字母大写, 不用点分隔(所含单词首字母大写); 常数命名规则同函数, 但需使用一个k 开头.正例: avg.clicks反例: avg_Clicks ,avgClicksFunctionName正例: CalculateAvgClicks反例: calculate_avg_clicks ,calculateAvgClicks函数命名应为动词或动词性短语.例外: 当创建一个含类(class) 属性的对象时, 函数名(也是constructor) 和类名(class) 应当匹配(例如, lm).kConstantName语法单行长度最大单行长度为80 个字符.缩进使用两个空格来缩进代码. 永远不要使用制表符或混合使用二者.例外: 当括号内发生折行时, 所折行与括号内的第一个字符对齐.空白在所有二元操作符(=, +, -, <-, 等等) 的两侧加上空格.例外: 在函数调用中传递参数时= 两边的空格可加可不加.不可在逗号前加空格, 逗号后总须加空格.正例:tabPrior<- table(df[df$daysFromOpt< 0, "campaignid"]) total <- sum(x[, 1]) total <- sum(x[1, ])反例:tabPrior<- table(df[df$daysFromOpt<0, "campaignid"]) # 在'<' 两侧需要增加空格tabPrior<- table(df[df$daysFromOpt< 0,"campaignid"]) # 逗号后需要一个空格tabPrior<- table(df[df$daysFromOpt< 0, "campaignid"]) # 在<- 前需要一个空格tabPrior<-table(df[df$daysFromOpt< 0, "campaignid"]) # 在<- 两侧需要增加空格total <- sum(x[,1]) # 逗号后需要一个空格total <- sum(x[ ,1]) # 逗号后需要一个空格, 而非逗号之前在前括号前加一个空格, 函数调用时除外.正例:if (debug)反例:if(debug)多加空格(即, 在行内使用多于一个空格) 也是可以的, 如果这样做能够改善等号或箭头(<-) 的对齐效果.plot(x = xCoord, y = dataMat[, makeColName(metric, ptiles[1], "roiOpt")], ylim = ylim, xlab = "dates", ylab = metric, main = (paste(metric, " for 3 samples ", sep="")))不要向圆括号或方括号中的代码两侧加入空格.例外: 逗号后总须加空格.正例:if (debug) x[1, ]反例:if ( debug ) # debug 的两边不要加空格x[1,] # 需要在逗号后加一个空格花括号前括号永远不应该独占一行; 后括号应当总是独占一行. 您可以在代码块只含单个语句时省略花括号; 但在处理这类单个语句时, 您必须前后一致地要么全部使用花括号, 或者全部不用花括号.if (is.null(ylim)) {ylim<- c(0, 0.06)}或(不可混用)if (is.null(ylim))ylim<- c(0, 0.06)总在新起的一行开始书写代码块的主体.反例:if (is.null(ylim)) ylim<- c(0, 0.06)if (is.null(ylim)) {ylim<- c(0, 0.06)}赋值使用<- 进行赋值, 不用= 赋值.正例:x <- 5反例:x = 5分号不要以分号结束一行, 也不要利用分号在同一行放多于一个命令. (分号是毫无必要的, 并且为了与其他Google编码风格指南保持一致, 此处同样略去.)代码组织总体布局和顺序如果所有人都以相同顺序安排代码内容, 我们就可以更加轻松快速地阅读并理解他人的脚本了.版权声明注释作者信息注释文件描述注释, 包括程序的用途, 输入和输出source() 和library() 语句函数定义要执行的语句, 如果有的话(例如, print, plot)单元测试应在另一个名为原始的文件名_unittest.R的独立文件中进行.注释准则注释您的代码. 整行注释应以# 后接一个空格开始.行内短注释应在代码后接两个空格, #, 再接一个空格.# Create histogram of frequency of campaigns by pct budget spent. hist(df$pctSpent, breaks = "scott", # method for choosing number of buckets main = "Histogram: fraction budget spent bycampaignid", xlab = "Fraction of budget spent", ylab = "Frequency (count of campaignids)")函数的定义和调用函数定义应首先列出无默认值的参数, 然后再列出有默认值的参数.函数定义和函数调用中, 允许每行写多个参数; 折行只允许在赋值语句外进行.正例:PredictCTR<- function(query, property, numDays, showPlot = TRUE)反例:PredictCTR<- function(query, property, numDays, showPlot = TRUE)理想情况下, 单元测试应该充当函数调用的样例(对于包中的程序来说).函数文档函数在定义行下方都应当紧接一个注释区. 这些注释应当由如下内容组成: 此函数的一句话描述; 此函数的参数列表, 用Args: 表示, 对每个参数的描述(包括数据类型); 以及对于返回值的描述, 以Returns:表示. 这些注释应当描述得足够充分, 这样调用者无须阅读函数中的任何代码即可使用此函数.示例函数CalculateSampleCovariance<- function(x, y, verbose = TRUE) { # Computes the sample covariance between two vectors. # # Args: # x: One of two vectors whose sample covariance is to be calculated. # y: The other vector. x and y must have the same length, greater than one, # with no missing values. # verbose: If TRUE, prints sample covariance; if not, not. Default is TRUE. # # Returns: # The sample covariance between x and y. n <- length(x) # Error handling if (n <= 1 || n != length(y)) { stop("Arguments x and y have invalid lengths: ", length(x), " and ", length(y), ".") } if (TRUE %in% is.na(x) || TRUE %in% is.na(y)) { stop(" Arguments x and y must not have missing values.") } covariance <- var(x, y) if (verbose) cat("Covariance = ", round(covariance, 4), ".\n", sep = "") return(covariance) }TODO 书写风格编码时通篇使用一种一致的风格来书写TODO.TODO(您的用户名): 所要采取行动的明确描述语言Attach使用attach 造成错误的可能数不胜数. 避免使用它.函数错误(error) 应当使用stop() 抛出.对象和方法S 语言中有两套面向对象系统, S3 和S4, 在R 中这两套均可使用. S3 方法的可交互性更强, 更加灵活, 反之, S4 方法更加正式和严格. (对这两套系统的说明, 参见Thomas Lumley 的文章“Programmer’s Niche: A Simple Class, in S3 and S4″, 发表于R News 4/1, 2004, 33 –36 页: /doc/Rnews/Rnews_2004-1.pdf.)这里推荐使用S3 对象和方法, 除非您有很强烈的理由去使用S4 对象和方法. 使用S4 对象的一个主要理由是在C++ 代码中直接使用对象. 使用一个S4 泛型/方法的主要理由是对双参数的分发.避免混用S3 和S4: S4 方法会忽略S3 中的继承, 反之亦然.例外除非有不去这样做的好理由, 否则应当遵循以上描述的编码惯例. 例外包括遗留代码的维护和对第三方代码的修改.结语遵守常识,前后一致.如果您在编辑现有代码, 花几分钟看看代码的上下文并弄清它的风格. 如果其他人在if 语句周围使用了空格, 那您也应该这样做. 如果他们的注释是用星号组成的小盒子围起来的, 那您也要这样写。
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++Style GuideRevision 3.188 Benjy 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 summaries Table of ContentsImportant 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.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 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: #ifndef FOO_BAR_BAZ_H_ #define FOO_BAR_BAZ_H_ ... #endif//FOO_BAR_BAZ_H_Header File Dependencieslink ▽Don'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 or const 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 Header FilesThe#define GuardHeader File DependenciesInline FunctionsThe-inl.h FilesFunction Parameter OrderingNames and Order of Includes ScopingNamespacesNested ClassesNonmember,Static Member,and Global FunctionsLocal VariablesStatic and Global Variables ClassesDoing Work in ConstructorsDefault ConstructorsExplicit ConstructorsCopy ConstructorsStructs vs.ClassesInheritanceMultiple InheritanceInterfacesOperator OverloadingAccess ControlDeclaration OrderWrite Short Functions Google-Specific MagicSmart Pointerscpplint Other C++FeaturesReference ArgumentsFunction OverloadingDefault ArgumentsVariable-Length Arrays and alloca()FriendsExceptionsRun-Time Type Information(RTTI)CastingStreamsPreincrement and PredecrementUse of constInteger Types64-bit PortabilityPreprocessor Macros0 and NULLsizeofBoostC++0x NamingGeneral Naming RulesFile NamesType NamesVariable NamesConstant NamesFunction NamesNamespace NamesEnumerator NamesMacro NamesExceptions to Naming Rules CommentsComment StyleFile CommentsClass CommentsFunction CommentsVariable CommentsImplementation CommentsPunctuation,Spelling and GrammarTODO CommentsDeprecation Comments FormattingLine LengthNon-ASCII CharactersSpaces vs.TabsFunction Declarations and DefinitionsFunction CallsConditionalsLoops and Switch StatementsPointer and Reference ExpressionsBoolean ExpressionsReturn ValuesVariable and Array InitializationPreprocessor DirectivesClass FormatConstructor Initializer ListsNamespace FormattingHorizontal WhitespaceVertical Whitespace Exceptions to the RulesExisting Non-conformant CodeWindows Codedeclaration.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 Functionslink▽Define 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 ually 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 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 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(often classes/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 descendants 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 as #include"base/logging.h"In dir/ or dir/foo_,whose main purpose is to implement or test the stuff in dir2/foo2.h,order your includes as follows: 1dir2/foo2.h(preferred location—see details below).2 C system files.3C++system files.4Other libraries'.h files.5Your 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 .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 includes in google-awesome-project/src/foo/internal/ might look like this:#include"foo/public/fooserver.h"//Preferred location.#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"ScopingNamespaceslink▽Unnamed 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∙Unnamed namespaces are allowed and even encouraged files,to avoid runtime naming conflicts: namespace{//This is in file.//The content of a namespace is not indentedenum{kUnused,kEOF,kError};//Commonly used tokens.bool AtEof(){return pos_==kEOF;}//Uses our namespace's EOF.}//namespaceHowever,file-scope declarations that are associated with a particular class may be declared in that class as types,static data members or 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 other namespaces://In the.h filenamespace mynamespace{//All declarations are within the namespace scope.//Notice the lack of indentation.class MyClass{public:...void Foo();};}//namespace mynamespace//In filenamespace mynamespace{//Definition of functions is within scope of the namespace.void MyClass::Foo(){...}}//namespace mynamespaceThe file might have more complex detail,including the need to reference classes in other namespaces.#include"a.h"DEFINE_bool(someflag,false,"dummy flag");class C;//Forward declaration of class C in the global namespace.namespace a{class A;}//Forward declaration of a::A.namespace b{...code for b...//Code goes against the left margin.}//namespace b∙Do not declare anything in namespace std,not even forward declarations of standard library classes.Declaring entities in namespace std is undefined behavior,i.e.,not portable.To declare entities from the standard library,include the appropriate header file.∙You may not use a using-directive to make all names from a namespace available.//Forbidden--This pollutes the namespace.using namespace foo;∙You may use a using-declaration anywhere in file,and in functions,methods or classes in.h files.//OK files.//Must be in a function,method or class in.h files.using::foo::bar;∙Namespace aliases are allowed anywhere in file,anywhere inside the named namespace that wraps an entire.h file,and in functions and methods.//Shorten access to some commonly used names files.namespace fbz=::foo::bar::baz;//Shorten access to some commonly used names(in a.h file).namespace librarian{//The following alias is available to all files including//this header(in namespace librarian)://alias names should therefore be chosen consistently//within a project.namespace pd_s=::pipeline_diagnostics::sidetable;inline void my_inline_function(){//namespace alias local to a function(or method).namespace fbz=::foo::bar::baz;...}}//namespace librarianNote 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 Classeslink▽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.Definition:A class can define another class within it;this is also called a member class.class Foo{private://Bar is a member class,nested within Foo.class Bar{...};};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 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 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 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.int i;i=f();//Bad--initialization separate from declaration.int j=g();//Good--declaration has initialization.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.while(const char*p=strchr(str,'/'))str=p+1;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.//Inefficient implementation:for(int i=0;i<1000000;++i){Foo f;//My ctor and dtor get called 1000000 times each.f.DoSomething(i);}It may be more efficient to declare such a variable used in a loop outside that loop:Foo f;//My ctor and dtor get called once each.for(int i=0;i<1000000;++i){f.DoSomething(i);}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 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 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 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(),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 an explicit 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 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 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,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).For convenience,a DISALLOW_COPY_AND_ASSIGN macro can be used://A macro to disallow the copy constructor and operator=functions//This should be used in the private:declarations for a class#define DISALLOW_COPY_AND_ASSIGN(TypeName)\TypeName(const TypeName&);\void operator=(const TypeName&)Then,in class Foo:class Foo{public:Foo(int f);~Foo();private:DISALLOW_COPY_AND_ASSIGN(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 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.。
Docs » C++ 风格指南 - 内容目录 » 11. 结束语
11. 结束语
运用常识和判断力, 并且保持一致.
编辑代码时, 花点时间看看项目中的其它代码, 并熟悉其风格. 如果其它代码中if语句使用空格, 那么你也要使用. 如果其中的注释用星号 (*) 围成一个盒子状, 那么你同样要这么做.
风格指南的重点在于提供一个通用的编程规范, 这样大家可以把精力集中在实现内容而不是表现形式上. 我们展示的是一个总体的的风格规范, 但局部风格也很重要, 如果你在一个文件中新加的代码和原有代码风格相去甚远, 这就破坏了文件本身的整体美观, 也让打乱读者在阅读代码时的节奏, 所以要尽量避免.
好了, 关于编码风格写的够多了; 代码本身才更有趣. 尽情享受吧!。
背景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/按如下方式保护:#ifndef FOO_BAR_BAZ_H_#define FOO_BAR_BAZ_H_...#endif 头文件依赖使用前置声明(forward declarations)尽量减少.h文件中#include的数量。
Google V8是一款用于执行JavaScript代码的开源JavaScript引擎,主要用于Google Chrome浏览器。
下面是一个简单的介绍,展示如何在C++代码中使用Google V8编写JavaScript。
1. 引入V8 头文件:#include <v8.h>2. 初始化V8:v8::V8::Initialize();3. 创建一个V8 上下文:v8::Isolate* isolate = v8::Isolate::New();v8::Isolate::Scope isolateScope(isolate);v8::HandleScope handleScope(isolate);v8::Local<v8::Context> context = v8::Context::New(isolate);v8::Context::Scope contextScope(context);4. 编写JavaScript 代码:v8::Local<v8::String> source = v8::String::NewFromUtf8(isolate, "console.lo g('Hello, V8!');");5. 编译和运行JavaScript 代码:v8::Local<v8::Script> script = v8::Script::Compile(context, source).ToLocalC hecked();v8::Local<v8::Value> result = script->Run(context).ToLocalChecked();6. 将JavaScript 结果转换为C++ 数据:v8::String::Utf8Value utf8(isolate, result);printf("JavaScript result: %s\n", *utf8);7. 清理资源:isolate->Dispose();v8::V8::Dispose();这是一个非常简单的例子,展示了如何使用V8在C++中执行一段简单的J avaScript代码。
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.。
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 powerbrings 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 allowingcoders 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 wenonetheless 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 thatthese features can cause. This guide lists these features and explains why their use isrestricted.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 thelanguage.Header FilesIn general, every .cc file should have an associated .h file. There are some commonexceptions, 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 andperformance 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 project foo should have the following guard:Don't use an 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/or return values, of type Foo. (One exception is if an argument Foo or const Foo& has a non-explicit,one-argument constructor, in which case we need the full definition to supportautomatic 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 ofdestructors, 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 neverexecuted).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 recursivefunctions should not be inline. The main reason for making a virtual function inline is to placeits definition in the class, either for convenience or to document its behavior, e.g., foraccessors 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 properlybelongs 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 classdefinition. 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 (oftenclasses/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 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:ScopingNamespacesUnnamed 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 notcollide.Cons:Namespaces can be confusing, because they provide an additional (hierarchical) axis ofnaming, 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∙Unnamed namespaces are allowed and even encouraged in .cc files, to avoidHowever, file-scope declarations that are associated with a particular class may bedeclared in that class as types, static data members or 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 other namespaces:The typical .cc file might have more complex detail, including the need to referenceclasses in other namespaces.∙Do not declare anything in namespace std, not even forward declarations of standard library classes. Declaring entities in namespace std is undefined behavior, i.e., not portable. To declare entities from the standard library, include the appropriate header file.∙You may use a using-declaration anywhere in a .cc file, and in functions, methods or∙Namespace aliases are allowed anywhere in a .cc file, anywhere inside the namedNote that an alias in a .h file is visible to everyone #including that file, so publicheaders (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 assmall 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 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. Nonmemberfunctions 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 introduceunnecessary coupling and -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 anunnamed namespace or static age (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 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 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 containsa reference to that string.As a result we only allow static variables to contain POD data. This rule completelydisallows 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 mustbe 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 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 problemeven 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(), possibly breaking some implicitassumptions in the constructor code. For instance, gflags will not yet have beeninitialized.Decision:If your object requires non-trivial initialization, consider having an explicit Init() method. In particular, constructors should not call virtual 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 adefault 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 defaultconstructor, 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 anassignment 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 botha 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 correspondingdefinition (so that any attempt to use them results in a error).For convenience, a DISALLOW_COPY_AND_ASSIGN macro can be used:Then, in class Foo: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 ownsemantic 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 associatedconstants, but lack any functionality other than access/setting the data members. Theaccessing/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 interface inheritance, in which only method names are inherited.Pros:Implementation inheritance reduces code size by re-using the base class code as itspecializes 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 beincluding 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 have an 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。
google编程规范
谷歌编程规范是一套由谷歌公司制定的程序设计标准,旨在提高代码的质量、可读性和可维护性。
以下是谷歌编程规范的主要内容,共计1000个字。
1. 缩进和空格:使用两个空格进行代码缩进,不使用制表符。
在操作符和操作数之间使用空格,但在逗号和分号之前不使用空格。
2. 命名规范:使用有描述性和可理解的名称来命名变量、函数和类。
变量名使用小写字母,多个单词之间使用下划线分隔。
函数和类的名称使用驼峰命名法。
3. 注释:在关键部分的代码上方添加注释,解释代码的目的、原因和实现细节。
注释应该清晰、简洁且易于理解。
代码本身应该是自解释的,不需要过多的注释。
4. 函数和方法:函数应该小而简单,只做一件事情。
函数的名称应该描述函数的功能。
避免使用全局变量,使用参数和返回值来传递数据。
5. 类和对象:类应该具有单一责任,只负责一个方面的功能。
类的名称应该是名词或名词短语。
类的方法应该有描述性的名称,并且只负责一个特定的任务。
6. 异常处理:在可能发生异常的地方使用异常处理机制。
捕获异常后应该对其进行适当的处理,而不是简单地忽略或打印错
误信息。
7. 错误处理:使用错误码、异常或错误对象来表示错误,并提供错误处理机制。
不要使用返回特定值来表示错误,这会导致代码的可读性和可维护性下降。
8. 数据结构:使用适当的数据结构来存储和操作数据。
选择合适的数据结构对于代码的性能和效率至关重要。
9. 条件语句和循环:使用简洁和明确的条件语句和循环。
避免使用过多的嵌套和复杂的逻辑操作。
10. 单元测试:编写单元测试来验证代码的正确性和健壮性。
确保测试覆盖了所有可能的情况,并且测试结果应该是可预测和可重现的。
11. 文档:编写清晰、详细和易于理解的文档来解释代码的功能和用法。
文档应该包括示例代码和使用示例。
12. 版本控制:使用版本控制系统来管理代码的版本。
定期提交代码,并写明清晰的提交消息。
以上是谷歌编程规范的主要内容,这些规范可以帮助开发者编写高质量、易读和易维护的代码。
遵守这些规范可以提高代码的质量和效率,并使团队的协作更加顺畅。
谷歌编程规范是编写优秀代码的基础,也是谷歌开发者社区的共同标准。