您好,欢迎光临本网站![请登录][注册会员]  
文件名称: Google C++ Style Guide
  所属分类: C++
  开发工具:
  文件大小: 477kb
  下载次数: 0
  上传时间: 2019-04-19
  提 供 者: dev****
 详细说明: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.In general, every.cc file should have an associated. h file. There are some common exceptionS, such as unittest 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 G?G?Self-contained Headers Header files should be self-contained and end in. h, Files that are meant for textual inclusion, but are not headers should end in.inc. Separate -inl.h headers are disallowed All header files should be self-contained. In other words, users and refactoring tools should not have to adhere to special conditions in order to include the header Specifically, a header should have header guards, should include all other headers it needs, and should not require any particular symbols to be defined There are rare cases where a file is not meant to be self-contained but instead is meant to be textually included at a specific point in the code. Examples are files that need to be included multiple times or platform-specific extensions that essentially are part of other headers. Such files should use the file extension inc If a template or inline function is declared in a. h file, define it in that same file. The definitions of these constructs must be included into every. cc file that uses them, or the program may fail to link in some build configurations Do not move these definitions to separate -inl. h files As an exception, a function template that is explicitly instantiated for all relevant sets of template arguments, or that is a private member of a class, may be defined in the only cc file that instantiates the template GGThe#define Guard All header files should have #define guards to prevent multiple inclusion. The format of the symbol name should be 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 GeGP Forward Declarations You may forward declare ordinary classes in order to avoid unnecessary #includes Definition A forward declaration" is a declaration of a class function, or template without an associated definition, #include lines can often be replaced with forward declarations of whatever symbols are actually used by the client code Pros Unnecessary #includes force the compiler to open more files and process more input They can also force your code to be recompiled more often, due to changes in the header Cons It can be difficult to determine the correct form of a forward declaration in the presence of features like templates, typedefs, default parameters, and using declarations It can be difficult to determine whether a forward declaration or a full #include is needed for a given piece of code, particularly when implicit conversion operations are involved. In extreme cases, replacing an #include with a forward declaration can silently change the meaning of code Forward declaring multiple symbols from a header can be more verbose than simply #includeing the header Forward declarations of functions and templates can prevent the header owners from making otherwise-compatible changes to their AP Is; for example, widening a parameter type, or adding a template parameter with a default value Forward declaring symbols from namespace std: usually yields undefined behavior Structuring code to enable forward declarations (e. g. using pointer members instead of object members)can make the code slower and more complex The practical efficiency benefits of forward declarations are unproven Decision: When using a function declared in a header file, always #include that header When using a class template, prefer to # include its header file When using an ordinary class, relying on a forward declaration is OK, but be wary of situations where a forward declaration may be insufficient or incorrect when in doubt, just #include the appropriate header Do not replace data members with pointers just to avoid an #include Please see names and order of includes for rules about when to # include a header Inline Functions 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 functions size, inlining it can cause the code size to increase or decrease Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache Decision: a decent rule of thumb is to not inline a function if it is more than 10 lines long. Beware of destructors, which are often longer than they appear because of implicit member- and base-destructor calls! Another useful rule of thumb: it's typically not cost effective to inline functions with loops or switch statements(unless, in the common case, the loop or switch statement is never executed) It is important to know that functions are not always inlined even if they are declared as such; for example, virtual and recursive functions are not normally inlined. Usually recursive functions should not be inline. The main reason for making a virtual function inline is to place its definition in the class, either for convenience or to document its behavior, e.g., for accessors and mutators Function Parameter Ordering 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 GO. Names and Order of Includes Use standard order for readability and to avoid hidden dependencies: Related header, 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/foo. cc or dir/foo test. cc, whose main purpose is to implement or test the stuff in dir2/foo2.h, order your includes as follows 1. dir2/foo2.h 2. C system files 3. C++ system files 4. Other libraries.h files 5. Your project's. h files With the preferred ordering, if dir2/foo2 h omits any necessary includes, the build of dir/foo. cc or dir/foo test. cc will break. Thus. this rule ensures that build breaks show up first for the people working on these files, not for innocent people in other packages dir/foo. cc and dir2 /foo2 h are usually in the same directory (e.g base/basictypes test cc and base/basictypes. h), but may sometimes be in different directories too Within each section the includes should be ordered alphabetically. Note that older code might not conform to this rule and should be fixed when convenient You should include all the headers that define the symbols you rely upon(except in cases of forward declaration). If you rely on symbols from bar. h, don' t count on the fact that you included foo. h which(currently)includes bar. h: include bar. h yourself, unless foo. h explicitly demonstrates its intent to provide you the symbols of bar. h. However, any includes present in the related header do not need to be included again in the related cc(i.e, foo. cc can rely on foo. h's includes) For example, the includes in google-awesome-project/src/foo/internal/fooserver cc might look like this #include foo/server/fooserverh include include finc lude #inc lude include"base/basictypesh include base/commandlineflagsh finc lude " foo/server/bar. h" Exception: Sometimes, system-specific code needs conditional includes Such code can put conditional includes after other includes. Of course, keep your system-specific code small and localized. Example finc lude"foo /public/fooserver h include"base/port.h"// For LANG CXX11 #ifdef LANG CXX11 finc lude fendi// LANG CXX11 caGScoping G NAmespaces 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. Do not use inline namespaces 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, project l: Foo and project2: Foo are now distinct symbols that do not collide Inline namespaces automatically place their names in the enclosing scope. Consider the following snippet, for example namespace X f inline namespace Y i void foo ()i The expressions x: Y:: foo() and X:: foo ( )are interchangeable. Inline namespaces are primarily intended for ABl compatibility across versions 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 Inline namespaces, in particular, can be confusing because names aren t actually restricted to the namespace where they are declared. They are only useful as part of some larger versioning polIcy Use of unnamed namespaces in header files can easily cause violations of the C++ One Definition Rule(ODR) Decision: Use namespaces according to the policy described below. Terminate namespaces with comments as shown in the given examples Unnamed Namespaces Unnamed namespaces are allowed and even encouraged in. cc files, to avoid link time naming conflicts namespace t // This is in a.cc / The content of a namespace is not indented This function is guaranteed not to generate a colliding //with other symbols at link time, and is only visible t / callers in this cc file bool UpdateInternals(robber* f, int newval)t )//namespace However, 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 e Do not use unnamed namespaces in. h files Named Namespaces Named 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 file namespace mynamespace i //All declarations are within the namespace scope Notice the lack of indentation class MyClass t public: void Foo oi // name space mynamespace / In the . cc file name space mynamespace t / Definition of functions is within scope of the namespa void MyClass: Foo([ 3 / namespace myname space The typical. cc file might have more complex detail, including the need to reference classes in other namespaces 并inc1ude"a.h DEFINE bool( someflag, false,"dummy flag" )i class C: / Forward declaration of class c in the global namespace a[ class A;1 //Forward declaration of a:: A namespace b i 。,, code for b。, //Code goes against the left ma // 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 a. cc file, and in functions, methods or classes in h files // Ok in . cc files. / Must be in a function, method or class in .h files using : foo: bar i Namespace aliases are allowed anywhere in a. cc file, anywhere inside the named namespace that wraps an entire . h file, and in functions and methods / shorten access to some commonly used names in cc file namespace fbz =: foo: bar:: baz / Shorten access to some commonly used names (in a . h fi namespace librarian / The following alias is available to all files includin / 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()i / namespace alias local to a function (or method namespace fbz = : foo: bar: baz; 17/namespace librarian Note that an alias in a. h file is visible to everyone #including that file, so public headers(those available outside a project) and headers transitively #included by them, should avoid defining aliases, as part of the general goal of keeping public APIs as small as possible Do not use inline namespaces Nested Classes Although you may use public nested classes when they are part of an interface, consider a namespace to keep declarations out of the global scope Definition a class can define another class within it this is also called a member class class Foo t private Bar is a member class, nested within Foo class Bar i 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 functions c Prefer nonmember functions within a namespace or static member functions to global functions; use completely global functions rarely Pros nonmember functions in a namespace avoids polluting the global namespace g Nonmember and static member functions can be useful in some situations Putti Cons Nonmember and static member functions may make more sense as members of a new class, especially if they access external resources or have significant dependencies Decision Sometimes it is useful, or even necessary, to define a function not bound to a class instance, Such a function can be either a static member or a nonmember function Nonmember functions should not depend on external variables, and should nearly always exist in a namespace. Rather than creating classes only to group static member functions which do not share static data, use namespaces instead Functions defined in the same compilation unit as production classes may introduce unnecessary coupling and link-time dependencies when directly called from other compilation units; static member functions are particularly susceptible to this. Consider extracting a new class, or placing the functions in a namespace possibly in a separate library If you must define a nonmember function and it is only needed in its. cc file, use an unnamed namespace or static linkage (eg static int Foo()[.3 to limit its
(系统自动生成,下载前可以参看下载内容)

下载文件列表

相关说明

  • 本站资源为会员上传分享交流与学习,如有侵犯您的权益,请联系我们删除.
  • 本站是交换下载平台,提供交流渠道,下载内容来自于网络,除下载问题外,其它问题请自行百度
  • 本站已设置防盗链,请勿用迅雷、QQ旋风等多线程下载软件下载资源,下载后用WinRAR最新版进行解压.
  • 如果您发现内容无法下载,请稍后再次尝试;或者到消费记录里找到下载记录反馈给我们.
  • 下载后发现下载的内容跟说明不相乎,请到消费记录里找到下载记录反馈给我们,经确认后退回积分.
  • 如下载前有疑问,可以通过点击"提供者"的名字,查看对方的联系方式,联系对方咨询.
 相关搜索: GoogleC++StyleGuide
 输入关键字,在本站1000多万海量源码库中尽情搜索: