From patchwork Mon Jun 18 22:28:35 2012 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Lawrence Crowl X-Patchwork-Id: 165620 Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@bilbo.ozlabs.org Received: from sourceware.org (server1.sourceware.org [209.132.180.131]) by ozlabs.org (Postfix) with SMTP id AF766B6FBC for ; Tue, 19 Jun 2012 08:29:19 +1000 (EST) Comment: DKIM? See http://www.dkim.org DKIM-Signature: v=1; a=rsa-sha1; c=relaxed/relaxed; d=gcc.gnu.org; s=default; x=1340663361; h=Comment: DomainKey-Signature:Received:Received:Received:Received:Received: MIME-Version:Received:Received:In-Reply-To:References:Date: Message-ID:Subject:From:To:Cc:Content-Type:Mailing-List: Precedence:List-Id:List-Unsubscribe:List-Archive:List-Post: List-Help:Sender:Delivered-To; bh=YZsqfmldj+VbM3HnZBp5PDIcmsU=; b=yVBVXD8UggZ+BnIscxDBATgWJ0RXLvvAw8WYw9AEPtqAllEC6jyeitPr1MTkJW nrYUh/IsjnkNvnXrrpWyi1H6NZog7XIo+vQcBbIi6o/6mb6jwuEwFASp7aHqz/j8 1lxGbehDddxkwBKqtfxbfl45IHPyx36cxNtQ6xPbkv7o8= Comment: DomainKeys? See http://antispam.yahoo.com/domainkeys DomainKey-Signature: a=rsa-sha1; q=dns; c=nofws; s=default; d=gcc.gnu.org; h=Received:Received:X-SWARE-Spam-Status:X-Spam-Check-By:Received:Received:X-Google-DKIM-Signature:Received:MIME-Version:Received:Received:In-Reply-To:References:Date:Message-ID:Subject:From:To:Cc:Content-Type:X-System-Of-Record:X-Gm-Message-State:X-IsSubscribed:Mailing-List:Precedence:List-Id:List-Unsubscribe:List-Archive:List-Post:List-Help:Sender:Delivered-To; b=nSCmc1x5eS7tfrCOvrOHmQuREaXdCYWTZ1pOH7Ycjz1i7gZ1XUlnr5aGuMA8DE AMBDFr7d7uAd+W25ATo8GqKuL/jANs2PRM8Ijli9Hg+i4UnXIKy3gDuiLlSnpzTj XtR7uz0tRyLvqiMlYVsCnbTu4bKsurJD93bfnMeTQgPXA=; Received: (qmail 6141 invoked by alias); 18 Jun 2012 22:29:09 -0000 Received: (qmail 6098 invoked by uid 22791); 18 Jun 2012 22:28:56 -0000 X-SWARE-Spam-Status: No, hits=-4.4 required=5.0 tests=AWL, BAYES_50, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, KHOP_RCVD_TRUST, KHOP_THREADED, RCVD_IN_DNSWL_LOW, RCVD_IN_HOSTKARMA_YE, T_RP_MATCHES_RCVD X-Spam-Check-By: sourceware.org Received: from mail-yx0-f175.google.com (HELO mail-yx0-f175.google.com) (209.85.213.175) by sourceware.org (qpsmtpd/0.43rc1) with ESMTP; Mon, 18 Jun 2012 22:28:36 +0000 Received: by yenl13 with SMTP id l13so4365836yen.20 for ; Mon, 18 Jun 2012 15:28:35 -0700 (PDT) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20120113; h=mime-version:in-reply-to:references:date:message-id:subject:from:to :cc:content-type:x-system-of-record:x-gm-message-state; bh=kBzq2dCIH0t9cByFbkPeNjpjXkWnxe4A/1kGH0KDy1o=; b=OYWCpZ/0Rm++B+WjH9ZHlDHohc1O+TY9opCT2I7PtYn4HsH3tVY6UNLYxHblJBBpU7 o8zIHIilpdozCVbWOIhqFYw7adzeVB1s9oRI/kC5YccmnZOTCPQvV1hevPOF7vsw98qJ g58AcNu0FDZvUTvtylPF47dNOnSkuYnPnnq6nPI/ypwO2mABtxkg/6BSq4hZ+PSdxLZc SDYehVZdoPJwY+HT4bwSDRpPGs1A2LuTL0pLBLOTkQ/nXYjLiiafmDi/flkewj+9bmFM PtkaZBrgLgnP+UmJ9EP8l7k+oer6rc+TJzpvbqwP+u8pbbh1vAZVX5sohBiTMhV/XgYO AApA== Received: by 10.50.41.226 with SMTP id i2mr10234854igl.4.1340058515456; Mon, 18 Jun 2012 15:28:35 -0700 (PDT) MIME-Version: 1.0 Received: by 10.50.41.226 with SMTP id i2mr10234843igl.4.1340058515218; Mon, 18 Jun 2012 15:28:35 -0700 (PDT) Received: by 10.231.83.211 with HTTP; Mon, 18 Jun 2012 15:28:35 -0700 (PDT) In-Reply-To: References: Date: Mon, 18 Jun 2012 15:28:35 -0700 Message-ID: Subject: Re: [wwwdocs] Update coding conventions for C++ From: Lawrence Crowl To: gcc-patches List Cc: Diego Novillo , Ian Lance Taylor , Benjamin Kosnik , Gabriel Dos Reis X-System-Of-Record: true X-Gm-Message-State: ALoCoQnVcA51Rs33mb6DADFpuzJoDeYQbYy6SaG0NpFZ3XctlvUhmpVzUXjhV2MxRuwSnU7eAHqKZElYjkYnzIzWanqiVIPDF/otgz+lIqmqB4mmFEhRhOfd/+XpXWZNbGn/ykuTvYYrG9Fjskw7IvU0jQKZ9UG9KCzZv0Wm8ZsDw848/XMRalYP4etio/S58GDh54zuSDkd X-IsSubscribed: yes Mailing-List: contact gcc-patches-help@gcc.gnu.org; run by ezmlm Precedence: bulk List-Id: List-Unsubscribe: List-Archive: List-Post: List-Help: Sender: gcc-patches-owner@gcc.gnu.org Delivered-To: mailing list gcc-patches@gcc.gnu.org This patch updates the coding conventions to C++. The primary source file is codingconventions.html. The coding conventions now refer to a new file, codingrationale.html, providing the rationale for some of the C++ conventions. The two files in question are attached whole for your convenience. The "Portability" section has some changes. The "Miscellaneous Conventions" section moves later and become part of the "C and C++ Language Conventions" section. The bulk of the change consists of additions to the "C and C++ Language Conventions" section and the addition of an entirely new "C++ Language Conventions" section. I added a table of contents. I have removed lines from the around the html tag, as they are causing my mail to be rejected. If you get this message twice, you now know why. :-) Please review. +

+ + + Index: codingconventions.html =================================================================== RCS file: /cvs/gcc/wwwdocs/htdocs/codingconventions.html,v retrieving revision 1.66 diff -u -u -r1.66 codingconventions.html --- codingconventions.html 19 Feb 2012 00:45:34 -0000 1.66 +++ codingconventions.html 18 Jun 2012 22:04:49 -0000 @@ -1,4 +1,8 @@ GCC Coding Conventions @@ -15,8 +19,56 @@ code to follow these conventions, it is best to send changes to follow the conventions separately from any other changes to the code.

+

+Documentation
+ChangeLogs
+Portability
+Makefiles
+Testsuite Conventions
+Diagnostics Conventions
+Spelling, terminology and markup
+C and C++ Language Conventions
+    Compiler Options
+    Language Use
+        Assertions
+        Character Testing
+        Error Node Testing
+        Parameters Affecting Generated Code
+        Inlining Functions
+    Formatting Conventions
+        Line Length
+        Names
+        Expressions
+        Function Calls
+C++ Language Conventions
+    Language Use
+        Variable Definitions
+        Struct Definitions
+        Class Definitions
+        Constructors and Destructors
+        Conversions
+        Overloading Functions
+        Overloading Operators
+        Default Arguments
+        Inlining Functions
+        Templates
+        Namespaces
+        RTTI and dynamic_cast
+        Other Casts
+        Exceptions
+        The Standard Library
+    Formatting Conventions
+        Names
+        Struct Definitions
+        Class Definitions
+        Class Member Definitions
+        Templates
+        Extern "C"
+        Namespaces
+

-

Documentation

+ +

Documentation

Documentation, both of user interfaces and of internals, must be maintained and kept up to date. In particular:

@@ -43,7 +95,7 @@ -

ChangeLogs

+

ChangeLogs

GCC requires ChangeLog entries for documentation changes; for the web pages (apart from java/ and libstdc++/) the CVS @@ -71,20 +123,61 @@ java/58 is the actual number of the PR) at the top of the ChangeLog entry.

-

Portability

+

Portability

There are strict requirements for portability of code in GCC to -older systems whose compilers do not implement all of the ISO C standard. -GCC requires at least an ANSI C89 or ISO C90 host compiler, and code -should avoid pre-standard style function definitions, unnecessary -function prototypes and use of the now deprecated @code{PARAMS} macro. +older systems whose compilers do not implement all of the +latest ISO C and C++ standards. +

+ +

+The directories +gcc, libcpp and fixincludes +may use C++03. +They may also use the long long type +if the host C++ compiler supports it. +Furthermore, +these directories should also be compatible with C++11. +

+ +

+The directories libiberty and libdecnumber must use C +and require at least an ANSI C89 or ISO C90 host compiler. +C code should avoid pre-standard style function definitions, unnecessary +function prototypes and use of the now deprecated PARAMS macro. See README.Portability for details of some of the portability problems that may arise. Some of these problems are warned about by gcc -Wtraditional, which is included in the default warning options in a bootstrap. -(Code outside the C front end is only compiled by GCC, so such -requirements do not apply to it.)

+

+ +

+Every version of GCC must be buildable by the previous version of GCC. +This rule helps ensure smooth development of the next version. +However, it doesn't help so much when you do not have a previous version. +So, the more important rule is that every version must bootstrap, +which means that version can develop itself. +Note that this statement does not preclude +a need to build GCC with other compilers. +

+ +

+We will periodically pick a stable version of GCC, +and require that that version of GCC be able to build +all versions of GCC up to and including the next stable version. +E.g., we may decide that all newer versions of GCC +should be buildable with GCC 4.3.5. +

+ +

+It is desirable that it be possible to build GCC +with C++ compilers other than GCC itself. +If testing reveals that reasonably recent versions of non-GCC C++ compilers +cannot compile GCC, +then GCC code should be adjusted accordingly. +(Avoiding unusual language constructs helps immensely.) +

The programs included in GCC are linked with the libiberty library, which will replace some standard @@ -108,12 +201,6 @@ the release cycle, to reduce the risk involved in fixing a problem that only shows up on one particular system.

-

Avoid the use of identifiers or idioms that would prevent code -compiling with a C++ compiler. Identifiers such as new -or class, that are reserved words in C++, should not be -used as variables or field names. Explicit casts should be used to -convert between void* and other pointer types.

-

Function prototypes for extern functions should only occur in header files. Functions should be ordered within source files to minimize the number of function prototypes, by defining them before @@ -121,13 +208,13 @@ necessary, to break mutually recursive cycles.

-

Makefiles

+

Makefiles

touch should never be used in GCC Makefiles. Instead of touch foo always use $(STAMP) foo.

-

Testsuite Conventions

+

Testsuite Conventions

Every language or library feature, whether standard or a GNU extension, and every warning GCC can give, should have testcases @@ -157,7 +244,7 @@ to the test suite.

-

Diagnostics Conventions

+

Diagnostics Conventions

  • Use of the input_location global, and of the @@ -208,66 +295,7 @@
-

Miscellaneous Conventions

- -

Code should use gcc_assert(EXPR) to check invariants. -Use gcc_unreachable() to mark places that should never be -reachable (such as an unreachable default case of a -switch). Do not use gcc_assert(0) for such purposes, as -gcc_unreachable gives the compiler more information. The -assertions are enabled unless explicitly configured off with ---enable-checking=none. Do not use abort. -User input should never be validated by either gcc_assert -or gcc_unreachable. If the checks are expensive or the -compiler can reasonably carry on after the error, they may be -conditioned on --enable-checking.

- -

Code testing properties of characters from user source code should -use macros such as ISALPHA from safe-ctype.h -instead of the standard functions such as isalpha from -<ctype.h> to avoid any locale-dependency of the -language accepted.

- -

Code in GCC should use the following formatting conventions:

- - - - - - - - - - - - - - - - - -
Use......instead of
!x! x
~x~ x
-x (unary minus)- x
(foo) x (cast)(foo)x
*x (pointer dereference)* x
- - -

Macros names should be in ALL_CAPS when it's important -to be aware that it's a macro (e.g. accessors and simple predicates), -but in lowercase (e.g., size_int) where the macro is a -wrapper for efficiency that should be considered as a function; see -messages 1 -and 2.

- -

Testing for ERROR_MARKs should be done by comparing -against error_mark_node rather than by comparing the -TREE_CODE against ERROR_MARK; see message.

- -

Internal numeric parameters that may affect generated code should -be controlled by --param rather than being hardcoded.

- - -

Spelling, terminology and markup

+

Spelling, terminology and markup

The following conventions of spelling and terminology apply throughout GCC, including the manuals, web pages, diagnostics, @@ -645,5 +673,682 @@ + +

C and C++ Language Conventions

+ +

+The following conventions apply to both C and C++. +

+ + +

Compiler Options

+ +

+The compiler must build cleanly with -Wall -Wextra. +

+ + +

Language Use

+ + +

Assertions

+ +

Code should use gcc_assert(EXPR) to check invariants. +Use gcc_unreachable() to mark places that should never be +reachable (such as an unreachable default case of a +switch). Do not use gcc_assert(0) for such purposes, as +gcc_unreachable gives the compiler more information. The +assertions are enabled unless explicitly configured off with +--enable-checking=none. Do not use abort. +User input should never be validated by either gcc_assert +or gcc_unreachable. If the checks are expensive or the +compiler can reasonably carry on after the error, they may be +conditioned on --enable-checking.

+ + +

Character Testing

+ +

Code testing properties of characters from user source code should +use macros such as ISALPHA from safe-ctype.h +instead of the standard functions such as isalpha from +<ctype.h> to avoid any locale-dependency of the +language accepted.

+ + +

Error Node Testing

+ +

Testing for ERROR_MARKs should be done by comparing +against error_mark_node rather than by comparing the +TREE_CODE against ERROR_MARK; see message.

+ + +

Parameters Affecting Generated Code

+ +

Internal numeric parameters that may affect generated code should +be controlled by --param rather than being hardcoded.

+ + +

Inlining Functions

+ +

+Inlining functions only when +you have reason to believe that +the expansion of the function is smaller than a call to the function +or that inlining is significant to the run-time of the compiler. +

+ + +

Formatting Conventions

+ + +

Line Length

+ +

Lines shall be at most 80 columns.

+ + +

Names

+ +

+Macros names should be in ALL_CAPS +when it's important to be aware that it's a macro +(e.g. accessors and simple predicates), +but in lowercase (e.g., size_int) +where the macro is a wrapper for efficiency +that should be considered as a function; +see messages +1 +and 2. +

+ +

+Other names should be lower-case and separated by low_lines. +

+ + +

Expressions

+ +

+Code in GCC should use the following formatting conventions: +

+ + + + + + + + + + + + + + + + + + + + + + + +
ForUse......instead of
logical not!x! x
bitwise complement~x~ x
unary minus-x- x
cast(foo) x(foo)x
pointer dereference*x* x
+ + +

Function Calls

+ +

+All current GCC code uses a space between the function name +and the left parenthesis in a function call. +Essentially all C++ code omits that space, +which is more consistent with C++ syntax. +For the present we will retain the space. +It is possible that in the future we will switch the code with a flag day. +

+ + +

C++ Language Conventions

+ +

+The following conventions apply only to C++. +

+ +

+These conventions will change over time, +but changing them requires that a convincing rationale. +

+ + +

Language Use

+ +

+C++ is a complex language, +and we strive to use it in a manner that is not surprising. +So, the primary rule is to be reasonable. +Use a language feature in known good ways. +If you need to use a feature in an unusual way, +or a way that violates the "should" rules below, +seek guidance, review and feedback from the wider community. +

+ +

+All use of C++ features +is subject to the decisions of the maintainers of the relevant components. +(This restates something that is always true for gcc, +which is that +component maintainers make the final decisions about those components.) +

+ +

Variable Definitions

+ +

+Variables should be defined at the point of first use, +rather than at the top of the function. +The existing code obviously does not follow that rule, +so variables may be defined at the top of the function, +as in C90. +

+ +

+Variables may be simultaneously defined and tested in control expressions. +

+ +

+Rationale and Discussion +

+ + +

Struct Definitions

+ +

+Use the struct keyword for + +plain old data (POD) types. +

+ +

+Rationale and Discussion +

+ +

Class Definitions

+ +

+Use the class keyword for + +non-POD types. +

+ +

+A non-POD type will often (but not always) +have a declaration of a + +special member function. +If any one of these is declared, +then all should be either declared +or have an explicit comment saying that the default is intended. +

+ +

+Single inheritance is permitted. +Use public inheritance to describe interface inheritance, +i.e. 'is-a' relationships. +Use private and protected inheritance +to describe implementation inheritance. +Implementation inheritance can be expediant, +but think twice before using it in code +intended to last a long time. +

+ +

+You should not use multiple inheritance. +

+ +

+Think carefully about the size and performance impact +of virtual functions and virtual bases +before using them. +

+ +

+Prefer to make data members private. +

+ +

+Rationale and Discussion +

+ + +

Constructors and Destructors

+ +

+All constructors should initialize data members +in the member initializer list rather than in the body of the constructor. +

+ +

+A class with virtual functions or virtual bases +should have a virtual destructor. +

+ +

+Rationale and Discussion +

+ +

Conversions

+ +

+Single argument constructors should nearly always be declared explicit. +

+ +

+Conversion operators should be avoided. +

+ +

+Rationale and Discussion +

+ + +

Overloading Functions

+ +

+Overloading functions is permitted, +but take care to ensure that overloads are not surprising, +i.e. semantically identical or at least very similar. +Virtual functions should not be overloaded. +

+ +

+Rationale and Discussion +

+ + +

Overloading Operators

+ +

+Overloading operators is permitted, +but take care to ensure that overloads are not surprising. +Some unsurprising uses are +in the implementation of numeric types and +in following the C++ Standard Library's conventions. +In addition, overloaded operators, excepting the call operator, +should not be used for expensive implementations. +

+ +

+Rationale and Discussion +

+ + +

Default Arguments

+ +

+Default arguments are another type of function overloading, +and the same rules apply. +Default arguments must always be POD values, i.e. may not run constructors. +Virtual functions should not have default arguments. +

+ +

+Rationale and Discussion +

+ + +

Inlining Functions

+ +

+Constructors and destructors, even those with empty bodies, +are often much larger than programmers expect. +Prefer non-inline versions unless you have evidence +that the inline version is smaller or has a significant performance impact. +

+ + +

Templates

+ +

+To avoid excessive compiler size, +consider implementing non-trivial templates +on a non-template base class with void* parameters. +

+ + +

Namespaces

+ +

+Namespaces are encouraged. +All separable libraries should have a unique global namespace. +All individual tools should have a unique global namespace. +Nested include directories names should map to nested namespaces when possible. +

+ +

+Header files should have neither using directives +nor namespace-scope using declarations. +

+ +

+There is no alternative to using declarations +in class definitions to manage names within an inheritance hierarchy, +so they are necessarily permitted. +

+ +

+Rationale and Discussion +

+ +

RTTI and dynamic_cast

+ +

+Run-time type information (RTTI) is permitted +when certain non-default --enable-checking options are enabled, +so as to allow checkers to report dynamic types. +However, by default, RTTI is not permitted +and the compiler must build cleanly with -fno-rtti. +

+ +

+Rationale and Discussion +

+ + +

Other Casts

+ +

+C-style casts should not be used. +Instead, use C++-style casts. +

+ +

+Rationale and Discussion +

+ + +

Exceptions

+ +

+Exceptions and throw specifications are not permitted +and the compiler must build cleanly with -fno-exceptions. +

+ +

+Rationale and Discussion +

+ + +

The Standard Library

+ +

+Use of the standard library is permitted. +Note, however, that it is currently not usable with garbage collected data. +

+ +

+For compiler messages, indeed any text that needs i18n, +should continue to use the existing facilities. +

+ +

+For long-term code, at least for now, +we will continue to use printf style I/O +rather than <iostream> style I/O. +For quick debugging code, +<iostream> is permitted. +

+ +

+Rationale and Discussion +

+ + +

Formatting Conventions

+ + +

Names

+ +

+When structs and/or classes have member functions, +prefer to name data members with a trailing underscore. +

+ +

+Template parameter names should use CamelCase, +following the C++ Standard. +

+ +

+Rationale and Discussion +

+ + +

Struct Definitions

+ +

+Note that the rules for classes do not apply to structs. +Structs continue to behave as before. +

+ + +

Class Definitions

+ +

+If the entire class definition fits on a single line, put it on a single line. +Otherwise, use the following rules. +

+ +

+Indent protection labels by one space. +

+ +

+Indent class members by two spaces. +

+ +

+Prefer to put the entire class head on a single line. +

+ +

+class gnuclass : base {
+
+ +

+Otherwise, start the colon of the base list at the beginning of a line. +

+ +

+class a_rather_long_class_name
+: with_a_very_long_base_name, and_another_just_to_make_life_hard
+{
+  int member;
+};
+
+ +

+If the base clause exceeds one line, +move overflowing initializers to the next line and indent by two spaces. +

+ +

+class gnuclass
+: base1 <template_argument1>, base2 <template_argument1>,
+  base3 <template_argument1>, base4 <template_argument1>
+{
+  int member;
+};
+
+ +

+When defining a class, +

+
    +
  • first define all public types,
  • +
  • then define all non-public types,
  • +
  • then declare all public constructors,
  • +
  • then declare the public destructor,
  • +
  • then declare all public member functions,
  • +
  • then declare all public member variables,
  • +
  • then declare all non-public constructors,
  • +
  • then declare the non-public destructor,
  • +
  • then declare all non-public member functions, and
  • +
  • then declare all non-public member variables.
  • +
+ +

+Semantic constraints may require a different declaration order, +but seek to minimize the potential confusion. +

+ +

+Close a class definition +with a right brace, semicolon, optional closing comment, and a new line. +

+ +

+} // class gnuclass
+
+ + +

Class Member Definitions

+ +

+Define all members outside the class definition. +That is, there are no function bodies or member initializers +inside the class definition. +

+ +

+Prefer to put the entire member head on a single line. +

+ +

+gnuclass::gnuclass() : base_class()
+{
+  ...
+};
+
+ +

+When that is not possible, +place the colon of the initializer clause at the beginning of a line. +

+ +

+gnuclass::gnuclass()
+: base1(), base2(), member1(), member2(), member3(), member4()
+{
+  ...
+};
+
+ +

+If the initializer clause exceeds one line, +move overflowing initializers to the next line and indent by two spaces. +

+ +

+gnuclass::gnuclass()
+: base1(some_expression), base2(another_expression),
+  member1(my_expressions_everywhere)
+{
+  ...
+};
+
+ +

+If a C++ function name is long enough +to cause the first function parameter with its type to exceed 80 characters, +it should appear on the next line indented four spaces. +

+ +

+void
+very_long_class_name::very_long_function_name(
+    very_long_type_name arg)
+{
+
+ +

+Sometimes the class qualifier and function name together exceed 80 characters. +In this case, break the line before the :: operator. +We may wish to do so pre-emptively for all class member functions. +

+ +

+void
+very_long_template_class_name <with, a, great, many, arguments>
+::very_long_function_name(
+    very_long_type_name arg)
+{
+
+ + +

Templates

+ +

+A declaration following a template parameter list +should not have additional indentation. +

+ +

+Prefer typename over class +in template parameter lists. +

+ + +

Extern "C"

+ +

+Prefer an extern "C" block to a declaration qualifier. +

+ +

+Open an extern "C" block with the left brace on the same line. +

+ +

+extern "C" {
+
+ +

+Close an extern "C" block +with a right brace, optional closing comment, and a new line. +

+ +

+} // extern "C"
+
+ +

+Definitions within the body of a namespace are not indented. +

+ +

Namespaces

+ +

+Open a namespace with the namespace name +followed by a left brace and a new line. +

+ +

+namespace gnutool {
+
+ +

+Close a namespace +with a right brace, optional closing comment, and a new line. +

+ +

+} // namespace gnutool
+
+ +

+Definitions within the body of a namespace are not indented. +

+ + Index: codingrationale.html =================================================================== RCS file: codingrationale.html diff -N codingrationale.html --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ codingrationale.html 18 Jun 2012 22:04:49 -0000 @@ -0,0 +1,386 @@ + + +GCC Coding Conventions Rationale and Discussion + + + +

GCC Coding Conventions Rationale and Discussion

+ +

C and C++ Language Conventions

+ +

Language Use

+ +

Inlining Functions

+ +

+Inlining functions has a potential cost in object size, +working set size, compile time, and debuggablity. +These costs should not be borne without some evidence +that the inlining pays for itself. +

+ + +

C++ Language Conventions

+ +

Language Use

+ +

Variable Definitions

+ +

+Defining variables when they are first needed +reduces the cognitive burden on the programmer. +It also eases converting common sub-expressions +into a defined and reused variable. +

+ +

+Defining and testing variables in control expressions +has the same advantages as above. +In addition, it restricts the scope of the variable +to the region in which it is known to be sensible. +

+ +

+if (info *q = get_any_available_info ()) {
+  // q is known to be non-NULL, and so do useful processing.
+}
+
+ + +

Struct Definitions

+ +

+In the C++ standard, +structs and classes differ only in the default access rules. +We prefer to use these two keywords to signal more information. +

+ +

+Note that under this definition, +structs may have member functions. +This freedom is useful for transitional code. +

+ + +

Class Definitions

+ +

+Forgetting to write a special member function is a known programming problem. +Some authors recommend always defining all special member functions. +Such classes are less efficient. +First, these definitions may prevent the compiler +from passing the class in a register. +Second, these definitions may prevent the compiler +from using more efficient methods for copying. +Adding a comment that the default is intended +preserves the performance while ensuring that +the function was not forgotten. +

+ +

+FIXME: Discussion of deleting inappropraite special members. +Classes generally are either value classes or identity classes. +Copy constructors and assignment operators are fine for value classes. +They are often not appropriate to identity classes. +These classes should delete, or disable, these functions. +Marking such functions as follows +will enable compiling against C++03, +and later modifying them for C++11. +

+ +

+TypeName(const TypeName&) /*DELETED*/;
+void operator=(const TypeName&) /*DELETED*/;
+
+ +

+Multiple inheritance is confusing and rarely useful. +When it is needed though, there may be no substitute. +Seek guidance, review and feedback from the wider community. +

+ +

+Using virtual functions increases the size of instances of the class +by at least one pointer. +In heavily allocated types, such as trees, GIMPLE or RTL, +this size increase could have adverse performance impacts. +On the other hand, +virtual functions can often reduce the size of instances +by binding information into the virtual tables and the virtual functions. +For example, various type tags need not be present. +Other attributes can be inferred +from type and more general information, +or from extending the class hierarchy at the leaves. +So, even though trees are heavily allocated, +it remains to be seen whether virtual functions would increase the size. +Therefore virtual functions should be added in heavily allocated classes +only after size and performance studies. +However, virtual functions are acceptable where we use hooks today, +as they are already essentially virtual tables. +

+ +

+There are good reasons to make private +all data members of non-POD classes. +However, in converting from C to C++, +there is a necessary transition that has public data members. +

+ + +

Constructors and Destructors

+ +

+The compiler implicitly initializes all non-POD fields. +Any initialization in the body of the constructor implies extra work. +

+ +

+Polymorphic classes without a virtual destructor +are almost certainly incorrect. +

+ +

Conversions

+ +

+C++ uses single-argument constructors for implicit type conversion. +Wide use of implicit conversion can cause some very surprising results. +

+ +

+C++03 has no explicit conversion operators, +and hence using them cannot avoid suprises. +Wait for C++11. +

+ + +

Overloading Functions

+ +

+Function overloading can be confusing. +However, in some cases introducing new function names adds little value, +as in the current distinction +between build_index_type and build_index_2_type. +

+ +

+The essential problem is to use overloading in a way that +improves conciseness without introducing confusion. +To that end, consider the following advice. +

+ +

+You may overload if the overloaded name supports an action notion. +For example, the C++ standard's notion of swap. +

+ +

+You may not overload +when implicit conversions among argument types may yield unintended effects. +For example, +

+ +

+void swizzle (int arg);
+void swizzle (const char *arg);
+... swizzle (NULL); ...
+
+ +

+results in an unintended call to the int overload on some systems. +In practice, the problem that this restriction addresses +arises more from bad user-defined implicit conversion operators. +See ISO C++ + +N2437 +and +ISO C++ + +N2514. +

+ +

+You may overload if a single argument, in a single position, +has multiple representations. For example, +

+ +

+void append (const char *str);
+void append (std::string str);
+
+ +

+You may not overload +if more than one argument constitutes the representation of some data notion. +For example, in +

+ +

+void register (int house, const char *street, int zipcode);
+
+ +

+the arguments are a representation of addresses. +Instead, the overload should be on addresses. +

+ +

+void register(const Address &addr);
+
+ +

+This restriction cannot apply to constructors, +where the whole point is to collect representational data. +

+ +

+Address::Address (int house, const char *street, int zipcode);
+
+ +

+Notwithstanding the restrictions above, you may overload to detect errors. +That is, if unsigned numbers are good, but signed numbers are bad, +you could overload +

+ +

+void munch (unsigned int arg);
+void munch (int arg);
+
+ +

+and simply not define the signed int version. +Anyone using it would get a link-time error. +(The C++11 standard has a syntax +that enables compile-time detection of the problem.) +

+ + +

Overloading Operators

+ +

+Using [] to index a vector is unsurprising, +but using [] to query a database over a network +is bound to cause performance problems. +

+ + +

Default Arguments

+ +

+Expensive default arguments can cause hard-to-identify performance problems. +

+ +

+Default arguments cause confusion +when attempting to take the address of a function. +They clause client code taking the address of a function +to break when a default argument is replaced by a specialized overload. +So, default arguments should generally not be used +in customer-facing interfaces. +Consider function overloading instead. +

+ + +

Namespaces

+ +

+Putting using directives +or namespace-scope using declarations +into header files can change client code in surprising ways. +

+ +

+Using them within an implementation file can help conciseness. +

+ + +

RTTI and dynamic_cast

+ +

+Disabling RTTI will save space in the compiler. +

+ +

+Checking the type of a class at runtime usually indicates a design problem. +If you need classes to behave differently at runtime, use a virtual method. +If you need to know the type of a class for some other reason, +use an enum or a virtual member function +that coverts a pointer to the more derived class. +For example, +

+ +

+common_type *p = ....;
+if (specific_type *q = p->to_specific ()) {
+  // We have and can use a specific_type pointed to by q.
+}
+
+ +

Other Casts

+ +

+C++-style casts are very explicit in the intended transformation. +Making intent clear avoids bugs and helps with other programmers. +

+ + +

Exceptions

+ +

+The current compiler code is not exception safe. +

+ +

+Disabling exceptions will permit +the compiler itself to be slightly more optimized. +

+ +

+Aborting the compiler is a reasonable response to unexpected problems. +

+ +

+We would like the compiler to be exception safe, +to permit reconsideration of the exception convention. +This change would require a significant change in style, +adopting "resource acquisition is initialization" (RAII). +We would be using +shared_ptr (from TR1's <memory>) +or unique_ptr (from C++11). +

+ +

The Standard Library

+ +

+At present, C++ provides no great advantage for i18n. +GCC does type checking for printf arguments, +so the type insecurity of printf is moot, +but the clarity in layout persists. +For quick debugging output, <iostream> requires less work. +

+ +

Formatting Conventions

+ +

Names

+ +

+Naming data members with a trailing underscore +highlights the extra overhead of access to fields over local variables. +Think of the trailing underscore +like you would Pascal's postfix ^ dereference operator. +

+ +

+When using the above convention, +the constructor parameter names +and getter member function names +can use the more concise non-underscore form.