OSDN Git Service

2007-11-21 Jonathan Wakely <jwakely.gcc@gmail.com>
[pf3gnuchains/gcc-fork.git] / libstdc++-v3 / docs / html / 17_intro / C++STYLE
1
2 C++ Standard Library Coding Style Guidelines  
3 -------------------------------------
4
5 This library is written to appropriate C++ coding standards.  As such,
6 it is intended to precede the recommendations of the GNU Coding
7 Standard, which can be referenced in full here:
8
9 http://www.gnu.org/prep/standards/standards.html#Formatting
10
11 The rest of this is also interesting reading, but skip the "Design
12 Advice" part.
13
14 The GCC coding conventions are here, and are also useful:
15 http://gcc.gnu.org/codingconventions.html
16
17 In addition, because it doesn't seem to be stated explicitly anywhere
18 else, there is an 80 column source limit.
19
20 ChangeLog entries for member functions should use the
21 classname::member function name syntax as follows:
22
23 1999-04-15  Dennis Ritchie  <dr@att.com>
24
25         * src/basic_file.cc (__basic_file::open): Fix thinko in
26         _G_HAVE_IO_FILE_OPEN bits.
27
28 Notable areas of divergence from what may be previous local practice
29 (particularly for GNU C) include:
30
31 01. Pointers and references
32   char* p = "flop";
33   char& c = *p;
34      -NOT-
35   char *p = "flop";  // wrong
36   char &c = *p;      // wrong
37   
38     Reason: In C++, definitions are mixed with executable code.  Here,       
39             p is being initialized, not *p.  This is near-universal
40             practice among C++ programmers; it is normal for C hackers
41             to switch spontaneously as they gain experience.
42
43 02. Operator names and parentheses
44   operator==(type)
45      -NOT-
46   operator == (type)  // wrong
47      
48     Reason: The == is part of the function name.  Separating
49             it makes the declaration look like an expression. 
50
51 03. Function names and parentheses
52   void mangle()
53      -NOT-
54   void mangle ()  // wrong
55
56      Reason: no space before parentheses (except after a control-flow
57      keyword) is near-universal practice for C++.  It identifies the
58      parentheses as the function-call operator or declarator, as 
59      opposed to an expression or other overloaded use of parentheses.
60
61 04. Template function indentation
62   template<typename T>
63     void 
64     template_function(args)
65     { }
66       -NOT-
67   template<class T>
68   void template_function(args) {};
69   
70      Reason: In class definitions, without indentation whitespace is
71              needed both above and below the declaration to distinguish
72              it visually from other members.  (Also, re: "typename"
73              rather than "class".)  T often could be int, which is 
74              not a class.  ("class", here, is an anachronism.)
75
76 05. Template class indentation
77   template<typename _CharT, typename _Traits>
78     class basic_ios : public ios_base
79     {
80     public:
81       // Types:
82     };
83   -NOT-
84   template<class _CharT, class _Traits>
85   class basic_ios : public ios_base
86     {
87     public:
88       // Types:
89     };
90   -NOT-
91   template<class _CharT, class _Traits>
92     class basic_ios : public ios_base
93   {
94     public:
95       // Types:
96   };
97
98 06. Enumerators
99   enum
100   {
101     space = _ISspace,
102     print = _ISprint,
103     cntrl = _IScntrl
104   };
105   -NOT-
106   enum { space = _ISspace, print = _ISprint, cntrl = _IScntrl };
107
108 07. Member initialization lists
109    All one line, separate from class name.
110
111   gribble::gribble() 
112   : _M_private_data(0), _M_more_stuff(0), _M_helper(0);
113   { }
114   -NOT-
115   gribble::gribble() : _M_private_data(0), _M_more_stuff(0), _M_helper(0);
116   { }
117
118 08. Try/Catch blocks
119   try 
120     {
121       //
122     }   
123   catch (...)
124     {
125       //
126     }   
127   -NOT-
128   try {
129     // 
130   } catch(...) { 
131     //
132   }
133
134 09. Member functions declarations and definitions
135    Keywords such as extern, static, export, explicit, inline, etc
136    go on the line above the function name. Thus
137
138   virtual int   
139   foo()
140   -NOT-
141   virtual int foo()
142
143         Reason: GNU coding conventions dictate return types for functions
144         are on a separate line than the function name and parameter list
145         for definitions. For C++, where we have member functions that can
146         be either inline definitions or declarations, keeping to this
147         standard allows all member function names for a given class to be
148         aligned to the same margin, increasing readibility.
149
150
151 10. Invocation of member functions with "this->"
152    For non-uglified names, use this->name to call the function.
153
154   this->sync()
155   -NOT-
156   sync()
157
158         Reason: Koenig lookup.
159
160 11. Namespaces
161   namespace std
162   {
163     blah blah blah;
164   } // namespace std
165
166   -NOT-
167
168   namespace std {
169     blah blah blah;
170   } // namespace std
171
172 12. Spacing under protected and private in class declarations:
173    space above, none below
174    ie
175
176    public:
177      int foo;
178
179    -NOT-
180    public:
181    
182      int foo;
183
184 13. Spacing WRT return statements.
185    no extra spacing before returns, no parenthesis
186    ie
187
188    }
189    return __ret;
190
191    -NOT-
192    }
193
194    return __ret;
195
196    -NOT-
197
198    }
199    return (__ret);
200
201
202 14. Location of global variables.
203    All global variables of class type, whether in the "user visable"
204    space (e.g., cin) or the implementation namespace, must be defined
205    as a character array with the appropriate alignment and then later
206    re-initialized to the correct value.
207
208    This is due to startup issues on certain platforms, such as AIX.
209    For more explanation and examples, see src/globals.cc.  All such
210    variables should be contained in that file, for simplicity.
211
212 15. Exception abstractions
213     Use the exception abstractions found in functexcept.h, which allow
214     C++ programmers to use this library with -fno-exceptions. (Even if
215     that is rarely advisable, it's a necessary evil for backwards
216     compatibility.)
217
218 16. Exception error messages
219     All start with the name of the function where the exception is
220     thrown, and then (optional) descriptive text is added. Example:
221
222     __throw_logic_error(__N("basic_string::_S_construct NULL not valid"));
223
224     Reason: The verbose terminate handler prints out exception::what(),
225     as well as the typeinfo for the thrown exception. As this is the
226     default terminate handler, by putting location info into the
227     exception string, a very useful error message is printed out for
228     uncaught exceptions. So useful, in fact, that non-programmers can
229     give useful error messages, and programmers can intelligently
230     speculate what went wrong without even using a debugger.
231
232 17. The doxygen style guide to comments is a separate document,
233     see index.
234
235 The library currently has a mixture of GNU-C and modern C++ coding
236 styles.  The GNU C usages will be combed out gradually.
237
238 Name patterns:
239
240 For nonstandard names appearing in Standard headers, we are constrained 
241 to use names that begin with underscores.  This is called "uglification".
242 The convention is:
243
244   Local and argument names:  __[a-z].*
245
246     Examples:  __count  __ix  __s1  
247
248   Type names and template formal-argument names: _[A-Z][^_].*
249
250     Examples:  _Helper  _CharT  _N 
251
252   Member data and function names: _M_.*
253
254     Examples:  _M_num_elements  _M_initialize ()
255
256   Static data members, constants, and enumerations: _S_.*
257
258     Examples: _S_max_elements  _S_default_value
259
260 Don't use names in the same scope that differ only in the prefix, 
261 e.g. _S_top and _M_top.  See BADNAMES for a list of forbidden names.
262 (The most tempting of these seem to be and "_T" and "__sz".)
263
264 Names must never have "__" internally; it would confuse name
265 unmanglers on some targets.  Also, never use "__[0-9]", same reason.
266
267 --------------------------
268
269 [BY EXAMPLE]
270     
271 #ifndef  _HEADER_
272 #define  _HEADER_ 1
273
274 namespace std
275 {
276   class gribble
277   {
278   public:
279     gribble() throw();
280
281     gribble(const gribble&);
282
283     explicit 
284     gribble(int __howmany);
285
286     gribble& 
287     operator=(const gribble&);
288
289     virtual 
290     ~gribble() throw ();
291
292     // Start with a capital letter, end with a period.
293     inline void  
294     public_member(const char* __arg) const;
295
296     // In-class function definitions should be restricted to one-liners.
297     int 
298     one_line() { return 0 }
299
300     int 
301     two_lines(const char* arg) 
302     { return strchr(arg, 'a'); }
303
304     inline int 
305     three_lines();  // inline, but defined below.
306
307     // Note indentation.
308     template<typename _Formal_argument>
309       void 
310       public_template() const throw();
311
312     template<typename _Iterator>
313       void 
314       other_template();
315
316   private:
317     class _Helper;
318
319     int _M_private_data;
320     int _M_more_stuff;
321     _Helper* _M_helper;
322     int _M_private_function();
323
324     enum _Enum 
325       { 
326         _S_one, 
327         _S_two 
328       };
329
330     static void 
331     _S_initialize_library();
332   };
333
334 // More-or-less-standard language features described by lack, not presence.
335 # ifndef _G_NO_LONGLONG
336   extern long long _G_global_with_a_good_long_name;  // avoid globals!
337 # endif
338
339   // Avoid in-class inline definitions, define separately;
340   // likewise for member class definitions:
341   inline int
342   gribble::public_member() const
343   { int __local = 0; return __local; }
344
345   class gribble::_Helper
346   {
347     int _M_stuff;
348
349     friend class gribble;
350   };
351 }
352
353 // Names beginning with "__": only for arguments and
354 //   local variables; never use "__" in a type name, or
355 //   within any name; never use "__[0-9]".
356
357 #endif /* _HEADER_ */
358
359
360 namespace std 
361 {
362   template<typename T>  // notice: "typename", not "class", no space
363     long_return_value_type<with_many, args>  
364     function_name(char* pointer,               // "char *pointer" is wrong.
365                   char* argument, 
366                   const Reference& ref)
367     {
368       // int a_local;  /* wrong; see below. */
369       if (test) 
370       { 
371           nested code 
372       }
373     
374       int a_local = 0;  // declare variable at first use.
375
376       //  char a, b, *p;   /* wrong */
377       char a = 'a';
378       char b = a + 1;
379       char* c = "abc";  // each variable goes on its own line, always.
380
381       // except maybe here...
382       for (unsigned i = 0, mask = 1; mask; ++i, mask <<= 1) {
383           // ...
384       }
385     }
386   
387   gribble::gribble()
388   : _M_private_data(0), _M_more_stuff(0), _M_helper(0);
389   { }
390
391   inline int 
392   gribble::three_lines()
393   {
394     // doesn't fit in one line.
395   }
396 } // namespace std
397
398
399