blob: 1c5b321c56966a0211d95648507df75ed49a0d21 [file] [log] [blame]
Alexander Afanasyev766cea72014-04-24 19:16:42 -07001ndn-cxx Code Style and Coding Guidelines
2========================================
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07003
4Based on
5
6 * "C++ Programming Style Guidelines" by Geotechnical Software Services, Copyright © 1996 – 2011.
7 The original document is available at `<http://geosoft.no/development/cppstyle.html>`_
8
9 * NDN Platform "C++, C, C#, Java and JavaScript Code Guidelines".
10 The original document available at `<http://named-data.net/codebase/platform/documentation/ndn-platform-development-guidelines/cpp-code-guidelines/>`_
11
Junxiao Shi28af1dc2014-11-06 15:53:32 -0700121. Code layout
13--------------
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -070014
151.1. The code layout should generally follow the GNU coding standard layout for C,
16extended it to C++.
17
18 * Do not use tabs for indentation.
19 * Indentation spacing is 2 spaces.
20 * Lines should be within a reasonable range. Lines longer than 100 columns should
21 generally be avoided.
22
231.2. Whitespace
24
25 * Conventional operators (``if``, ``for``, ``while``, and others) should be
26 surrounded by a space character.
27 * Commas should be followed by a white space.
28 * Semicolons in for statments should be followed by a space character.
29
30 Examples:
31
32 .. code-block:: c++
33
34 a = (b + c) * d; // NOT: a=(b+c)*d
35
36 while (true) { // NOT: while(true)
37 ...
38
39 doSomething(a, b, c, d); // NOT: doSomething(a,b,c,d);
40
41 for (i = 0; i < 10; i++) { // NOT: for(i=0;i<10;i++){
42 ...
43
441.3. Namespaces should have the following form:
45
46 .. code-block:: c++
47
48 namespace example {
49
50 code;
51 moreCode;
52
53 } // namespace example
54
55 Note that code inside namespace is **not** indented. Avoid following:
56
57 .. code-block:: c++
58
59 // NOT
60 //
61 // namespace example {
62 //
63 // code;
64 // moreCode;
65 //
66 // } // namespace example
67
681.4. The class declarations should have the following form:
69
70 .. code-block:: c++
71
72 class SomeClass : public BaseClass
73 {
74 public:
75 ... <public methods> ...
76 protected:
77 ... <protected methods> ...
78 private:
79 ... <private methods> ...
80
81 public:
82 ... <public data> ...
83 protected:
84 ... <protected data> ...
85 private:
86 ... <private data> ...
87 };
88
89 ``public``, ``protected``, ``private`` may be repeated several times without
90 interleaving (e.g., public, public, public, private, private) if this allows better
91 readability of the code.
92
93 Nested classes can be defined in appropriate visibility section, either in methods
94 block, data block, or in a separate section (depending which one provides better code
95 readability).
96
971.5. Method and function definitions should have the following form:
98
99 .. code-block:: c++
100
101 void
102 someMethod()
103 {
104 ...
105 }
106
107 void
108 SomeClass::someMethod()
109 {
110 ...
111 }
112
1131.6. The ``if-else`` class of statements should have the following form:
114
115 .. code-block:: c++
116
117 if (condition) {
118 statements;
119 }
120
121 if (condition) {
122 statements;
123 }
124 else {
125 statements;
126 }
127
128 if (condition) {
129 statements;
130 }
131 else if (condition) {
132 statements;
133 }
134 else {
135 statements;
136 }
137
138 or (less preferred):
139
140 .. code-block:: c++
141
142 if (condition)
143 {
144 statements;
145 }
146 else if (condition)
147 {
148 statements;
149 }
150 else
151 {
152 statements;
153 }
154
1551.7. A ``for`` statement should have the following form:
156
157 .. code-block:: c++
158
159 for (initialization; condition; update) {
160 statements;
161 }
162
163 or (less preferred):
164
165 .. code-block:: c++
166
167 for (initialization; condition; update)
168 {
169 statements;
170 }
171
172 An empty for statement should have the following form:
173
174 .. code-block:: c++
175
176 for (initialization; condition; update)
177 ;
178
179 This emphasizes the fact that the for statement is empty and it makes it obvious for
180 the reader that this is intentional. Empty loops should be avoided however.
181
1821.8. A ``while`` statement should have the following form:
183
184 .. code-block:: c++
185
186 while (condition) {
187 statements;
188 }
189
190 or (less preferred):
191
192 .. code-block:: c++
193
194 while (condition)
195 {
196 statements;
197 }
198
1991.9. A ``do-while`` statement should have the following form:
200
201 .. code-block:: c++
202
203 do {
204 statements;
205 } while (condition);
206
2071.10. A ``switch`` statement should have the following form:
208
209 .. code-block:: c++
210
211 switch (condition) {
212 case ABC:
213 statements;
214 // Fallthrough
215
216 case DEF:
217 statements;
218 break;
219
220 case XYZ:
221 statements;
222 break;
223
224 default:
225 statements;
226 break;
227 }
228
229 or (less preferred):
230
231 .. code-block:: c++
232
233 switch (condition)
234 {
235 case ABC:
236 statements;
237 // Fallthrough
238
239 case DEF:
240 statements;
241 break;
242
243 case XYZ:
244 statements;
245 break;
246
247 default:
248 statements;
249 break;
250 }
251
252 The explicit ``Fallthrough`` comment should be included whenever there is a case
253 statement without a break statement. Leaving the break out is a common error, and it
254 must be made clear that it is intentional when it is not there.
255
2561.11. A ``try-catch`` statement should have the following form:
257
258 .. code-block:: c++
259
260 try {
261 statements;
262 }
263 catch (Exception& exception) {
264 statements;
265 }
266
267 or (less preferred):
268
269 .. code-block:: c++
270
271 try
272 {
273 statements;
274 }
275 catch (Exception& exception)
276 {
277 statements;
278 }
279
2801.12. The incompleteness of split lines must be made obvious.
281
282 .. code-block:: c++
283
284 totalSum = a + b + c +
285 d + e;
286 function(param1, param2,
287 param3);
288 for (int tableNo = 0; tableNo < nTables;
289 tableNo += tableStep) {
290 ...
291 }
292
293 Split lines occurs when a statement exceed the 80 column limit given above. It is
294 difficult to give rigid rules for how lines should be split, but the examples above should
295 give a general hint.In general:
296
297 * Break after a comma.
298 * Break after an operator.
299 * Align the new line with the beginning of the expression on the previous line.
300
301 Exceptions:
302
303 * The following is the standard practice with operator<<:
304
305 .. code-block:: c++
306
307 std::cout << "Something here "
308 << "Something there" << std::endl;
309
3101.13. When class variables need to be initialized in the constructor, the initialization
311should take the following form:
312
313 .. code-block:: c++
314
315 SomeClass::SomeClass(int value, const std::string& string)
316 : m_value(value)
317 , m_string(string)
318 ...
319 {
320 }
321
322 Each initialization should be put on a separate line, starting either with the colon
323 for the first initialization or with comma for all subsequent initializations.
324
Junxiao Shi45c13842014-11-02 15:36:04 -07003251.14. A range-based ``for`` statement should have the following form:
326
327 .. code-block:: c++
328
329 for (T i : range) {
330 statements;
331 }
332
Junxiao Shicf698182014-11-03 08:37:42 -07003331.15. A lambda expression should have the following form:
334
335 .. code-block:: c++
336
337 [&capture1, capture2] (T1 arg1, T2 arg2) {
338 statements;
339 }
340
341 [&capture1, capture2] (T1 arg1, T2 arg2) mutable {
342 statements;
343 }
344
345 [this] (T arg) {
346 statements;
347 }
348
349 If the function has no parameters, ``()`` should be omitted.
350
351 .. code-block:: c++
352
353 [&capture1, capture2] {
354 statements;
355 }
356
357 Capture-all (``[&]`` and ``[=]``) is permitted, but its usage should be minimized.
358 Only use capture-all when it significantly simplifies code and improves readability.
359
360 .. code-block:: c++
361
362 [&] (T arg) {
363 statements;
364 }
365
366 [=] (T arg) {
367 statements;
368 }
369
370 Trailing return type should be omitted. Write them only when compiler cannot deduce
371 return type automatically, or when it improves readability.
372 ``()`` is required by C++ standard when trailing return type is written.
373
374 .. code-block:: c++
375
376 [] (T arg) -> int {
377 statements;
378 }
379
380 [] () -> int {
381 statements;
382 }
383
384 If the function body has only one line, and the whole lambda expression can fit in one line,
385 the following form is also acceptable:
386
387 .. code-block:: c++
388
389 [&capture1, capture2] (T1 arg1, T2 arg2) { statement; }
390
391 No-op can be written in a more compact form:
392
393 .. code-block:: c++
394
395 []{}
396
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07003972. Naming Conventions
398---------------------
399
4002.1. C++ header files should have the extension ``.hpp``. Source files should have the
401extension ``.cpp``
402
403 File names should be all lower case. If the class name
404 is a composite of several words, each word in a file name should be separated with a
405 dash (-). A class should be declared in a header file and defined in a source file
406 where the name of the files match the name of the class.
407
408 ::
409
410 my-class.hpp, my-class.cpp
411
412
4132.2. Names representing types must be written in English in mixed case starting with upper case.
414
415 .. code-block:: c++
416
417 class MyClass;
418 class Line;
419 class SavingsAccount;
420
4212.3. Variable names must be written in English in mixed case starting with lower case.
422
423 .. code-block:: c++
424
425 MyClass myClass;
426 Line line;
427 SavingsAccount savingsAccount;
428 int theAnswerToLifeTheUniverseAndEverything;
429
4302.4. Named constants (including enumeration values) must be all uppercase using underscore
431to separate words.
432
433 .. code-block:: c++
434
435 const int MAX_ITERATIONS = 25;
436 const std::string COLOR_RED = "red";
437 static const double PI = 3.14;
438
439 In some cases, it is a better (or is the only way for complex constants in header-only
440 classes) to implement the value as a method:
441
442 .. code-block:: c++
443
444 int
445 getMaxIterations()
446 {
447 return 25;
448 }
449
4502.5. Names representing methods or functions must be commands starting with a verb and
451written in mixed case starting with lower case.
452
453 .. code-block:: c++
454
455 std::string
456 getName()
457 {
458 ...
459 }
460
461 double
462 computeTotalWidth()
463 {
464 ...
465 }
466
4672.6. Names representing namespaces should be all lowercase.
468
469 .. code-block:: c++
470
471 namespace model {
472 namespace analyzer {
473
474 ...
475
476 } // namespace analyzer
477 } // namespace model
478
4792.7. Names representing generic template types should be a single uppercase letter
480
481 .. code-block:: c++
482
483 template<class T> ...
484 template<class C, class D> ...
485
486 However, when template parameter represents a certain concept and expected to have a
487 certain interface, the name should be explicitly spelled out:
488
489 .. code-block:: c++
490
491 template<class FaceBase> ...
492 template<class Packet> ...
493
4942.8. Abbreviations and acronyms must not be uppercase when used as name.
495
496 .. code-block:: c++
497
498 exportHtmlSource(); // NOT: exportHTMLSource();
499 openDvdPlayer(); // NOT: openDVDPlayer();
500
5012.9. Global variables should have ``g_`` prefix
502
503 .. code-block:: c++
504
505 g_mainWindow.open();
506 g_applicationContext.getName();
507
508 In general, the use of global variables should be avoided. Consider using singleton
509 objects instead.
510
5112.10. Private class variables should have ``m_`` prefix. Static class variables should have
512``s_`` prefix.
513
514 .. code-block:: c++
515
516 class SomeClass
517 {
518 private:
519 int m_length;
520
521 static std::string s_name;
522 };
523
524
5252.11. Variables with a large scope should have long (explicit) names, variables with a small
526scope can have short names.
527
528 Scratch variables used for temporary storage or indices are best kept short. A
529 programmer reading such variables should be able to assume that its value is not used
530 outside of a few lines of code. Common scratch variables for integers are ``i``,
531 ``j``, ``k``, ``m``, ``n`` and for characters ``c`` and ``d``.
532
5332.12. The name of the object is implicit, and should be avoided in a method name.
534
535 .. code-block:: c++
536
537 line.getLength(); // NOT: line.getLineLength();
538
539 The latter seems natural in the class declaration, but proves superfluous in use, as
540 shown in the example.
541
5422.13. The terms ``get/set`` must be used where an attribute is accessed directly.
543
544 .. code-block:: c++
545
546 employee.getName();
547 employee.setName(name);
548
549 matrix.getElement(2, 4);
550 matrix.setElement(2, 4, value);
551
5522.14. The term ``compute`` can be used in methods where something is computed.
553
554 .. code-block:: c++
555
556 valueSet.computeAverage();
557 matrix.computeInverse()
558
559 Give the reader the immediate clue that this is a potentially time-consuming operation,
560 and if used repeatedly, he might consider caching the result. Consistent use of the term
561 enhances readability.
562
5632.15. The term ``find`` can be used in methods where something is looked up.
564
565 .. code-block:: c++
566
567 vertex.findNearestVertex();
568 matrix.findMinElement();
569
570 Give the reader the immediate clue that this is a simple look up method with a minimum
571 of computations involved. Consistent use of the term enhances readability.
572
5732.16. Plural form should be used on names representing a collection of objects.
574
575 .. code-block:: c++
576
577 vector<Point> points;
578 int values[];
579
580 Enhances readability since the name gives the user an immediate clue of the type of
581 the variable and the operations that can be performed on its elements.
582
5832.17. The prefix ``n`` should be used for variables representing a number of objects.
584
585 .. code-block:: c++
586
587 nPoints, nLines
588
589 The notation is taken from mathematics where it is an established convention for
590 indicating a number of objects.
591
592
5932.18. The suffix ``No`` should be used for variables representing an entity number.
594
595 .. code-block:: c++
596
597 tableNo, employeeNo
598
599 The notation is taken from mathematics where it is an established convention for
600 indicating an entity number. An elegant alternative is to prefix such variables with
601 an ``i``: ``iTable``, ``iEmployee``. This effectively makes them named iterators.
602
6032.19. The prefix ``is``, ``has``, ``need``, or similar should be used for boolean variables and
604methods.
605
606 .. code-block:: c++
607
608 isSet, isVisible, isFinished, isFound, isOpen
609 needToConvert, needToFinish
610
6112.20. Complement names must be used for complement operations, reducing complexity by
612symmetry.
613
614 ::
615
616 get/set, add/remove, create/destroy, start/stop, insert/delete,
617 increment/decrement, old/new, begin/end, first/last, up/down, min/max,
618 next/previous (and commonly used next/prev), open/close, show/hide,
619 suspend/resume, etc.
620
621 Pair ``insert/erase`` should be preferred. ``insert/delete`` can also be used if it
622 does not conflict with C++ delete keyword.
623
6242.21. Variable names should not include reference to variable type (do not use Hungarian
625notation).
626
627 .. code-block:: c++
628
629 Line* line; // NOT: Line* pLine;
630 // NOT: Line* linePtr;
631
632 size_t nPoints; // NOT lnPoints
633
634 char* name; // NOT szName
635
6362.22. Negated boolean variable names should be avoided.
637
638 .. code-block:: c++
639
640 bool isError; // NOT: isNoError
641 bool isFound; // NOT: isNotFound
642
6432.23. Enumeration constants recommended to prefix with a common type name.
644
645 .. code-block:: c++
646
647 enum Color {
648 COLOR_RED,
649 COLOR_GREEN,
650 COLOR_BLUE
651 };
652
6532.24. Exceptions can be suffixed with either ``Exception`` (e.g., ``SecurityException``) or
654``Error`` (e.g., ``SecurityError``).
655
656 The recommended method is to declare exception class ``Exception`` or ``Error`` as an
657 inner class, from which the exception is thrown. For example, when declaring class
658 ``Foo`` that can throw errors, one can write the following:
659
660 .. code-block:: c++
661
662 #include <stdexcept>
663
664 class Foo
665 {
666 class Error : public std::runtime_error
667 {
668 public:
669 explicit
670 Error(const std::string& what)
671 : std::runtime_error(what)
672 {
673 }
674 };
675 };
676
677 In addition to that, if class Foo is a base class or interface for some class
678 hierarchy, then child classes should should define their own ``Error`` or
679 ``Exception`` classes that are inherited from the parent's Error class.
680
681
6822.25. Functions (methods returning something) should be named after what they return and
683procedures (void methods) after what they do.
684
685 Increase readability. Makes it clear what the unit should do and especially all the
686 things it is not supposed to do. This again makes it easier to keep the code clean of
687 side effects.
688
6893. Miscellaneous
690----------------
691
6923.1. Exceptions can be used in the code, but should be used only in exceptional cases and
693not in the primary processing path.
694
6953.2. Header files must contain an include guard.
696
697 For example, header file located in ``module/class-name.hpp`` or in
698 ``src/module/class-name.hpp`` should have header guard in the following form:
699
700 .. code-block:: c++
701
702 #ifndef APP_MODULE_CLASS_NAME_HPP
703 #define APP_MODULE_CLASS_NAME_HPP
704 ...
705 #endif // APP_MODULE_CLASS_NAME_HPP
706
707 The name should follow the location of the file inside the source tree and prevents
708 naming conflicts. Header guard should be prefixed with the application/library name
709 to avoid conflicts with other packaged and libraries.
710
7113.3. Header files which are in the same source distribution should be included in
712``"quotes"``, if possible with a path relative to the source file. Header files for
713system and other external libraries should be included in ``<angle brackets>``.
714
715 .. code-block:: c++
716
717 #include <string>
718 #include <boost/lexical_cast.hpp>
719
720 #include "util/random.hpp"
721
7223.4. Include statements should be sorted and grouped. Sorted by their hierarchical position
723in the system with low level files included first. Leave an empty line between groups
724of include statements.
725
726 .. code-block:: c++
727
728 #include <fstream>
729 #include <iomanip>
730
731 #include <boost/lexical_cast.hpp>
732 #include <boost/regex.hpp>
733
734 #include "detail/pending-interest.hpp"
735 #include "util/random.hpp"
736
737
7383.5. Types that are local to one file only can be declared inside that file.
739
740
7413.6. Implicit conversion is generally allowed.
742
743 Implicit conversion between integer and floating point numbers can cause problems and
744 should be avoided.
745
746 Implicit conversion in single-argument constructor is usually undesirable. Therefore, all
747 single-argument constructors should be marked 'explicit', unless implicit conversion is
748 desirable. In that case, a comment should document the reason.
749
750 Avoid C-style casts. Use ``static_cast``, ``dynamic_cast``, ``reinterpret_cast``,
751 ``const_cast`` instead where appropriate. Use ``static_pointer_cast``,
752 ``dynamic_pointer_cast``, ``const_pointer_cast`` when dealing with ``shared_ptr``.
753
754
7553.7. Variables should be initialized where they are declared.
756
757 This ensures that variables are valid at any time. Sometimes it is impossible to
758 initialize a variable to a valid value where it is declared:
759
760 .. code-block:: c++
761
762 int x, y, z;
763 getCenter(&x, &y, &z);
764
765 In these cases it should be left uninitialized rather than initialized to some phony
766 value.
767
7683.8. In most cases, class instance variables should not be declared public.
769
770 The concepts of information hiding and encapsulation are violated by public variables. Use
771 private variables and access methods instead.
772
773 Exceptions to this rule:
774
775 * when the class is essentially a dumb data structure with no or minimal behavior
776 (equivalent to a C struct, also known as PODS). In this case it is appropriate to make
777 the instance variables public by using struct.
778
779 * when the class is used only inside the compilation unit, e.g., when implementing pImpl
780 idiom (aka Bridge pattern) or similar cases.
781
782
7833.9. C++ pointers and references should have their reference symbol next to the type rather
784than to the name.
785
786 .. code-block:: c++
787
788 float* x; // NOT: float *x;
789 int& y; // NOT: int &y;
790
7913.10. Implicit test for 0 should not be used other than for boolean variables and pointers.
792
793 .. code-block:: c++
794
795 if (nLines != 0) // NOT: if (nLines)
796 if (value != 0.0) // NOT: if (value)
797
7983.11. When checking if ``shared_ptr`` points to an object, explicit ``static_cast<bool>``
799must be used.
800
801 ``shared_ptr`` in C++11 (unlike ``boost::shared_ptr``) does not have implicit
802 conversion to bool.
803
8043.12. Loop variables should be initialized immediately before the loop.
805
806 .. code-block:: c++
807
808 isDone = false; // NOT: bool isDone = false;
809 while (!isDone) { // // other stuff
810 : // while (!isDone) {
811 } // :
812 // }
813
8143.13. The form while (true) should be used for infinite loops.
815
816 .. code-block:: c++
817
818 while (true) {
819 ...
820 }
821
822 // NOT:
823 for (;;) { // NO!
824 :
825 }
826 while (1) { // NO!
827 :
828 }
829
8303.14. Complex conditional expressions must be avoided. Introduce temporary boolean variables
831instead.
832
833 .. code-block:: c++
834
835 bool isFinished = (elementNo < 0) || (elementNo > maxElement);
836 bool isRepeatedEntry = elementNo == lastElement;
837 if (isFinished || isRepeatedEntry) {
838 ...
839 }
840
841 // NOT:
842 // if ((elementNo < 0) || (elementNo > maxElement) || elementNo == lastElement) {
843 // ...
844 // }
845
846 By assigning boolean variables to expressions, the program gets automatic
847 documentation. The construction will be easier to read, debug and maintain.
848
8493.15. The conditional should be put on a separate line.
850
851 .. code-block:: c++
852
853 if (isDone) // NOT: if (isDone) doCleanup();
854 doCleanup();
855
856 This is for debugging purposes. When writing on a single line, it is not apparent
857 whether the test is really true or not.
858
8593.16. Assignment statements in conditionals must be avoided.
860
861 .. code-block:: c++
862
863 File* fileHandle = open(fileName, "w");
864 if (!fileHandle) {
865 ...
866 }
867
868 // NOT
869 // if (!(fileHandle = open(fileName, "w"))) {
870 // ..
871 // }
872
8733.17. The use of magic numbers in the code should be avoided. Numbers other than 0 and 1
874should be considered declared as named constants instead.
875
876 If the number does not have an obvious meaning by itself, the readability is enhanced
877 by introducing a named constant instead. A different approach is to introduce a method
878 from which the constant can be accessed.
879
8803.18. Floating point constants should always be written with decimal point, at least one
881 decimal, and without omitting 0 before decimal point.
882
883 .. code-block:: c++
884
885 double total = 0.0; // NOT: double total = 0;
886 double someValue = 0.1; // NOT double someValue = .1;
887 double speed = 3.0e8; // NOT: double speed = 3e8;
888 double sum;
889 ...
890 sum = (a + b) * 10.0;
891
8923.19. ``goto`` should not be used.
893
894Goto statements violate the idea of structured code. Only in some very few cases (for
895instance breaking out of deeply nested structures) should goto be considered, and only if
896the alternative structured counterpart is proven to be less readable.
897
Junxiao Shi03b15b32014-10-30 21:10:25 -07008983.20. ``nullptr`` should be used to represent a null pointer, instead of "0" or "NULL".
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700899
9003.21. Logical units within a block should be separated by one blank line.
901
902 .. code-block:: c++
903
904 Matrix4x4 matrix = new Matrix4x4();
905
906 double cosAngle = Math.cos(angle);
907 double sinAngle = Math.sin(angle);
908
909 matrix.setElement(1, 1, cosAngle);
910 matrix.setElement(1, 2, sinAngle);
911 matrix.setElement(2, 1, -sinAngle);
912 matrix.setElement(2, 2, cosAngle);
913
914 multiply(matrix);
915
916 Enhance readability by introducing white space between logical units of a block.
917
9183.22. Variables in declarations can be left aligned.
919
920 .. code-block:: c++
921
922 AsciiFile* file;
923 int nPoints;
924 float x, y;
925
926 Enhance readability. The variables are easier to spot from the types by alignment.
927
9283.23. Use alignment wherever it enhances readability.
929
930 .. code-block:: c++
931
932 value = (potential * oilDensity) / constant1 +
933 (depth * waterDensity) / constant2 +
934 (zCoordinateValue * gasDensity) / constant3;
935
936 minPosition = computeDistance(min, x, y, z);
937 averagePosition = computeDistance(average, x, y, z);
938
939 There are a number of places in the code where white space can be included to enhance
940 readability even if this violates common guidelines. Many of these cases have to do
941 with code alignment. General guidelines on code alignment are difficult to give, but
942 the examples above should give a general clue.
943
9443.24. All comments should be written in English.
945
946 In an international environment English is the preferred language.
947
Alexander Afanasyevdfa52c42014-04-24 21:10:11 -07009483.25. Use ``//`` for all comments, including multi-line comments.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700949
950 .. code-block:: c++
951
952 // Comment spanning
953 // more than one line.
954
955 Since multilevel C-commenting is not supported, using ``//`` comments ensure that it
956 is always possible to comment out entire sections of a file using ``/* */`` for
957 debugging purposes etc.
958
959 There should be a space between the ``//`` and the actual comment, and comments should
960 always start with an upper case letter and end with a period.
961
962 However, method and class documentation comments should use ``/** */`` style for
963 Doxygen, JavaDoc and JSDoc.
964
9653.26. Comments should be included relative to their position in the code.
966
967 .. code-block:: c++
968
969 while (true) {
970 // Do something
971 something();
972 }
973
974 // NOT:
975 while (true) {
976 // Do something
977 something();
978 }
979
980 This is to avoid that the comments break the logical structure of the program.
Junxiao Shiae61aac2014-11-04 14:57:38 -0700981
9823.27. Use ``BOOST_ASSERT`` and ``BOOST_ASSERT_MSG`` for runtime assertions.
983
984 .. code-block:: c++
985
986 int x = 1;
987 int y = 2;
988 int z = x + y;
989 BOOST_ASSERT(z - y == x);
990
991 The expression passed to ``BOOST_ASSERT`` MUST NOT have side effects,
992 because it MAY NOT be evaluated in release builds.
993
9943.28. Use ``static_assert`` for static assertions.
995
Junxiao Shiae61aac2014-11-04 14:57:38 -0700996 .. code-block:: c++
997
998 class BaseClass
999 {
1000 };
1001
1002 class DerivedClass : public BaseClass
1003 {
1004 };
1005
1006 static_assert(std::is_base_of<BaseClass, DerivedClass>::value,
1007 "DerivedClass must inherit from BaseClass");
Junxiao Shic0a8c3b2014-11-08 12:09:05 -07001008
10093.29. ``auto`` type specifier MAY be used for local variables, if a human reader
1010 can easily deduce the actual type.
1011
1012 .. code-block:: c++
1013
1014 std::vector<int> intVector;
1015 auto i = intVector.find(4);
1016
1017 auto stringSet = std::make_shared<std::set<std::string>>();
1018
1019 ``auto`` SHOULD NOT be used if a human reader cannot easily deduce the actual type.
1020
1021 .. code-block:: c++
1022
1023 auto x = foo(); // BAD if the declaration of foo() isn't nearby
1024
1025 ``const auto&`` SHOULD be used to represent constant reference types.
1026 ``auto&&`` SHOULD be used to represent mutable reference types.
1027
1028 .. code-block:: c++
1029
1030 std::list<std::string> strings;
1031
1032 for (const auto& str : strings) {
1033 statements; // cannot modify `str`
1034 }
1035 for (auto&& str : strings) {
1036 statements; // can modify `str`
1037 }