-
Notifications
You must be signed in to change notification settings - Fork 18
/
coding_guidelines.html
2875 lines (2714 loc) · 138 KB
/
coding_guidelines.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<HTML xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcq="http://purl.org/dc/qualifiers/1.0/" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:fn="http://www.w3.org/2005/xpath-functions">
<HEAD>
<TITLE>ALICE O² C++ Coding Guidelines</TITLE>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<LINK HREF="http://www.google.com/favicon.ico" type="image/x-icon" rel="shortcut icon">
<LINK HREF="styleguide.css" type="text/css" rel="stylesheet">
<SCRIPT language="javascript" type="text/javascript">
function GetElementsByName(name) {
// Workaround a bug on old versions of opera.
if (document.getElementsByName) {
return document.getElementsByName(name);
} else {
return [document.getElementById(name)];
}
}
/**
* @param {string} bodyName The body name.
* @param {string} buttonName The button name.
* @param {function(boolean): boolean} getVisibility Computes the new
* visibility state, given the current one.
*/
function ChangeVisibility(bodyName, buttonName, getVisibility) {
var bodyElements = GetElementsByName(bodyName);
var linkElement = GetElementsByName('link-' + buttonName)[0];
if (bodyElements.length != 1) {
throw Error('ShowHideByName() got the wrong number of bodyElements: ' +
bodyElements.length);
} else {
var bodyElement = bodyElements[0];
var buttonElement = GetElementsByName(buttonName)[0];
var isVisible = bodyElement.style.display != "none";
if (getVisibility(isVisible)) {
bodyElement.style.display = "inline";
if(linkElement) linkElement.style.display = "block";
buttonElement.innerHTML = '▽';
} else {
bodyElement.style.display = "none";
if(linkElement) linkElement.style.display = "none";
buttonElement.innerHTML = '▶';
}
}
}
function ShowHideByName(namePrefix) {
var bodyName = namePrefix + '__body';
var buttonName = namePrefix + '__button';
ChangeVisibility(bodyName, buttonName, function(old) { return !old; });
}
function ShowByName(namePrefix) {
var bodyName = namePrefix + '__body';
var buttonName = namePrefix + '__button';
ChangeVisibility(bodyName, buttonName, function() { return true; });
}
function ToggleExtraByName(namePrefix) {
var bodyName = namePrefix + '__extra_body';
var buttonName = namePrefix + '__extra_button';
ChangeVisibility(bodyName, buttonName, function(old) { return !old; });
}
function ShowHideAll() {
var allButton = GetElementsByName("show_hide_all_button")[0];
if (allButton.innerHTML == '▽') {
allButton.innerHTML = '▶';
SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "showhide_button", "none", '▶');
} else {
allButton.innerHTML = '▽';
SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "showhide_button", "inline", '▽');
}
}
function ShowHideAllExtra() {
var allButton = GetElementsByName("show_hide_all_extra_button")[0];
// if you want to toggle also the summaries at the same time, uncomment these lines.
/*var allSummaries = GetElementsByName("show_hide_all_button")[0];
if(allButton.innerHTML == allSummaries.innerHTML) {
ShowHideAll();
}*/
if (allButton.innerHTML == '▽') {
allButton.innerHTML = '▶';
SetHiddenStateExtra(document.getElementsByTagName("body")[0].childNodes, "showhide_extrabutton", "none", '▶');
} else {
allButton.innerHTML = '▽';
SetHiddenStateExtra(document.getElementsByTagName("body")[0].childNodes, "showhide_extrabutton", "inline", '▽');
}
}
// Recursively sets state of all children
// of a particular node.
function SetHiddenState(root, buttonClass, newState, newButton) {
for (var i = 0; i != root.length; i++) {
SetHiddenState(root[i].childNodes, buttonClass, newState, newButton);
if (root[i].className == buttonClass) {
root[i].innerHTML = newButton;
}
if (root[i].className == 'stylepoint_body' ||
root[i].className == 'link_button') {
root[i].style.display = newState;
}
}
}
// Recursively sets state of all children
// of a particular node.
function SetHiddenStateExtra(root, buttonClass, newState, newButton) {
//console.log(" in sethiddenstateextra");
for (var i = 0; i != root.length; i++) {
SetHiddenStateExtra(root[i].childNodes, buttonClass, newState, newButton);
if (root[i].className == buttonClass) {
root[i].innerHTML = newButton;
}
if (root[i].className == 'stylepoint_extra') {
//console.log(" in stylepoint_extra");
root[i].style.display = newState;
}
}
}
function EndsWith(str, suffix) {
var l = str.length - suffix.length;
return l >= 0 && str.indexOf(suffix, l) == l;
}
function RefreshVisibilityFromHashParam() {
var hashRegexp = new RegExp('#([^&#]*)$');
var hashMatch = hashRegexp.exec(window.location.href);
var anchor = hashMatch && GetElementsByName(hashMatch[1])[0];
var node = anchor;
var suffix = '__body';
while (node) {
var id = node.id;
var matched = id && EndsWith(id, suffix);
if (matched) {
var len = id.length - suffix.length;
ShowByName(id.substring(0, len));
if (anchor.scrollIntoView) {
anchor.scrollIntoView();
}
return;
}
node = node.parentNode;
}
}
window.onhashchange = RefreshVisibilityFromHashParam;
window.onload = function() {
// if the URL contains "?showall=y", expand the details of all children
var showHideAllRegex = new RegExp("[\\?&](showall)=([^&#]*)");
var showHideAllValue = showHideAllRegex.exec(window.location.href);
if (showHideAllValue != null) {
if (showHideAllValue[2] == "y") {
SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "showhide_button",
"inline", '▽');
} else {
SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "showhide_button",
"none", '▶');
}
}
var showOneRegex = new RegExp("[\\?&](showone)=([^&#]*)");
var showOneValue = showOneRegex.exec(window.location.href);
if (showOneValue) {
ShowHideByName(showOneValue[2]);
}
RefreshVisibilityFromHashParam();
}
</SCRIPT>
</HEAD>
<BODY>
<H1>ALICE O² C++ Coding Guidelines</H1>
<address>
Vasco Barroso<br>
Alina GrigoraȘ<br>
Ivana Hřivnáčová<br>
Matthias Kretz<br>
Adriana Telesca<br>
Barthélémy von Haller<br>
</address>
<p align="right">
This document is based on the work of <br>
B. Weinberger, C. Silverstein, <br>
G. Eitzmann, M. Mentovai <br>
and T.Landray <br>
at <a href="http://google-styleguide.googlecode.com"> http://google-styleguide.googlecode.com</a>, <br>
C++ Google Style guide, Revision 3.274 <br>
under the <a rel="license" href="http://creativecommons.org/licenses/by/3.0/deed.en_US">CC-By 3.0 License</a>
</p>
<DIV style="margin-left: 50%; font-size: 75%;">
<P>
Each style point has a summary for which additional information is available
by toggling the accompanying arrow button that looks this way:
<SPAN class="showhide_button" style="margin-left: 0; float: none">▶</SPAN>.
You may toggle all summaries with the big arrow button:
</P>
<DIV style=" font-size: larger; margin-left: +2em;">
<SPAN class="showhide_button" style="font-size: 180%; float: none" onclick="javascript:ShowHideAll()" name="show_hide_all_button" id="show_hide_all_button">▶</SPAN>
Toggle all summaries
</DIV>
<DIV style=" font-size: larger; margin-left: +2em;">
<SPAN class="showhide_extrabutton" style="font-size: 180%; float: none" onclick="javascript:ShowHideAllExtra()" name="show_hide_all_extra_button" id="show_hide_all_extra_button">▶</SPAN>
Toggle all extra details
</DIV>
</DIV>
<DIV class="toc">
<DIV class="toc_title">Table of Contents</DIV>
<TABLE>
<TR valign="top" class="">
<TD><DIV class="toc_category"><A href="#Header_Files">Header Files</A></DIV></TD>
<TD><DIV class="toc_stylepoint">
<SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#The__define_Guard">The #define Guard</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Forward_Declarations">Forward Declarations</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Inline_Functions">Inline Functions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Names_and_Order_of_Includes">Names and Order of Includes</A></SPAN> </DIV></TD>
</TR>
<TR valign="top" class="">
<TD><DIV class="toc_category"><A href="#Namespaces">Namespaces</A></DIV></TD>
<TD><DIV class="toc_stylepoint">
<SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#General_guideline">General guideline</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Using_declarations_and_directives">Using declarations and directives</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Unnamed_namespaces">Unnamed namespaces</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Namespace_aliases">Namespace aliases</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#std_namespace">std namespace</A></SPAN> </DIV></TD>
</TR>
<TR valign="top" class="">
<TD><DIV class="toc_category"><A href="#Scoping">Scoping</A></DIV></TD>
<TD><DIV class="toc_stylepoint">
<SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Nonmember_and_Global_Functions">Nonmember and Global Functions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Local_Variables">Local Variables</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Variables_Initialization">Variables Initialization</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Brace_Initialization">Brace Initialization</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Global_Variables">Global Variables</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Global_variables_initialization">Global variables initialization</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Static_Variables_in_functions">Static Variables in functions</A></SPAN> </DIV></TD>
</TR>
<TR valign="top" class="">
<TD><DIV class="toc_category"><A href="#Classes">Classes</A></DIV></TD>
<TD><DIV class="toc_stylepoint">
<SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Initialization">Initialization</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Virtual_functions_in_constructors_and_destructors">Virtual functions in constructors and destructors</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Explicit_Constructors">Explicit Constructors</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Copy__and_Move_">Copy (and Move)</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Delegating_and_inheriting_constructors">Delegating and inheriting constructors</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Structs_vs._Classes">Structs vs. Classes</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Destructors">Destructors</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Inheritance">Inheritance</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Multiple_Inheritance">Multiple Inheritance</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Interfaces">Interfaces</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Operator_Overloading">Operator Overloading</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Access_Control">Access Control</A></SPAN> </DIV></TD>
</TR>
<TR valign="top" class="">
<TD><DIV class="toc_category"><A href="#Others">Others</A></DIV></TD>
<TD><DIV class="toc_stylepoint">
<SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Exceptions">Exceptions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Use_of_const">Use of const</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Use_of_constexpr">Use of constexpr</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Smart_Pointers">Smart Pointers</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Magic_numbers">Magic numbers</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Preprocessor_Macros">Preprocessor Macros</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Write_Short_Functions">Write Short Functions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Run-Time_Type_Information__RTTI_">Run-Time Type Information (RTTI)</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Casting">Casting</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Variable-Length_Arrays_and_alloca__">Variable-Length Arrays and alloca()</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Increment_and_Decrement_operators">Increment and Decrement operators</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Loops_and_Switch_Statements">Loops and Switch Statements</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Integer_Types">Integer Types</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Portability">Portability</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#0_and_nullptr">0 and nullptr</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#sizeof">sizeof</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#auto">auto</A></SPAN> </DIV></TD>
</TR>
<TR valign="top" class="">
<TD><DIV class="toc_category"><A href="#Exceptions_to_the_Rules">Exceptions to the Rules</A></DIV></TD>
<TD><DIV class="toc_stylepoint">
<SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Existing_Non-conformant_Code">Existing Non-conformant Code</A></SPAN> </DIV></TD>
</TR>
</TABLE>
</DIV>
<DIV class="">
<H2 name="Important_Note" id="Important_Note">Important Note</H2>
<DIV class="">
<H3><A name="Displaying_Hidden_Details_in_this_Guide" id="Displaying_Hidden_Details_in_this_Guide">Displaying Hidden Details in this Guide</A></H3>
<SPAN class="link_button" id="link-Displaying_Hidden_Details_in_this_Guide__button" name="link-Displaying_Hidden_Details_in_this_Guide__button"><A href="?showone=Displaying_Hidden_Details_in_this_Guide#Displaying_Hidden_Details_in_this_Guide">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Displaying_Hidden_Details_in_this_Guide')" name="Displaying_Hidden_Details_in_this_Guide__button" id="Displaying_Hidden_Details_in_this_Guide__button">▶</SPAN>
<DIV style="display:inline;" class="">
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. The first level of hidden information is
the subsection <i>Summary</i> in each rule and the second level of hidden information is the
optional subsection <i>Extra details and exceptions to the rule</i>. Click the arrow on the
left now, you should see "Hooray" appear below.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Displaying_Hidden_Details_in_this_Guide__body" id="Displaying_Hidden_Details_in_this_Guide__body" style="display: none">
<p>
Hooray! Now you know you can expand points to get more
details. Alternatively, there are an "expand all summaries"
and an "expand all summaries and extra details" at the
top of this document.
</p>
</DIV></DIV>
</DIV>
</DIV>
<DIV class="">
<H2 name="Background" id="Background">Background</H2>
<p>
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.
</p>
<p>
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.
</p>
<p>
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.
</p>
<p>
Note that this guide is not a C++ tutorial: we assume that the
reader is familiar with the language.
</p>
</DIV>
<DIV class="">
<H2 name="Header_Files" id="Header_Files">Header Files</H2>
<p>
In general, every <code>.cxx</code> file should have an associated
<code>.h</code> file. There are some common exceptions, such as
unittests
and small <code>.cxx</code> files containing just a <code>main()</code>
function.
</p>
<p>
Correct use of header files can make a huge difference to the
readability, size and performance of your code.
</p>
<p>
The following rules will guide you through the various pitfalls of
using header files.
</p>
<DIV class="">
<H3><A name="The__define_Guard" id="The__define_Guard">The #define Guard</A></H3>
<SPAN class="link_button" id="link-The__define_Guard__button" name="link-The__define_Guard__button"><A href="?showone=The__define_Guard#The__define_Guard">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('The__define_Guard')" name="The__define_Guard__button" id="The__define_Guard__button">▶</SPAN>
<DIV style="display:inline;" class="">
All header files should have <code>#define</code> guards to
prevent multiple inclusion. The format of the symbol name
should be
<code><i><PROJECT></i>_<i><PATH></i>_<i><FILE></i>_H_</code>.
Avoid using <code>#pragma once</code>.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="The__define_Guard__body" id="The__define_Guard__body" style="display: none">
<p>
To guarantee uniqueness, they should be based on the full path
in a project's source tree. For example, the file
<code>foo/src/bar/myFile.h</code> in project <code>foo</code> should
have the following guard:
</p>
<DIV class=""><PRE>#ifndef FOO_BAR_MYFILE_H_
#define FOO_BAR_MYFILE_H_
...
#endif // FOO_BAR_MYFILE_H_</PRE></DIV>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Forward_Declarations" id="Forward_Declarations">Forward Declarations</A></H3>
<SPAN class="link_button" id="link-Forward_Declarations__button" name="link-Forward_Declarations__button"><A href="?showone=Forward_Declarations#Forward_Declarations">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Forward_Declarations')" name="Forward_Declarations__button" id="Forward_Declarations__button">▶</SPAN>
<DIV style="display:inline;" class="">
You may forward declare ordinary classes in order to avoid
unnecessary <code>#include</code>s.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Forward_Declarations__body" id="Forward_Declarations__body" style="display: none">
<P class="">
<SPAN class="stylepoint_section">Definition: </SPAN>
A "forward declaration" is a declaration of a class, function,
or template without an associated definition. <code>#include</code>
lines can often be replaced with forward declarations of whatever
symbols are actually used by the client code.
</P>
<P class="">
<SPAN class="stylepoint_section">Pros: </SPAN>
<ul>
<li>Unnecessary <code>#include</code>s force the compiler to open
more files and process more input.</li>
<li>They can also force your code to be recompiled more often, due
to changes in the header.</li>
</ul>
</P>
<P class="">
<SPAN class="stylepoint_section">Cons: </SPAN>
<ul>
<li>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.</li>
<li>Forward declaring multiple symbols from a header can be more
verbose than simply including the header.</li>
<li>Forward declarations of functions and templates can prevent
the header owners from making otherwise-compatible changes to
their APIs; for example, widening a parameter type, or adding
a template parameter with a default value.</li>
<li>Forward declaring symbols from namespace <code>std::</code>
usually yields undefined behavior.</li>
</ul>
</P>
<P class="">
<SPAN class="stylepoint_section">Decision: </SPAN>
<ul>
<li>When using a function declared in a header file, always
<code>#include</code> that header.</li>
<li>When using a class template, prefer to <code>#include</code> its
header file.</li>
<li>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
<code>#include</code> the appropriate header.</li>
<li>Do not replace data members with pointers just to avoid an
<code>#include</code>.</li>
</ul>
Always <code>#include</code> the file that actually provides the
declarations/definitions you need; do not rely on the symbol being
brought in transitively via headers not directly included. One
exception is that <code>myFile.cxx</code> may rely on
<code>#include</code>s and forward declarations from its corresponding
header file <code>myFile.h</code>.
</P>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Inline_Functions" id="Inline_Functions">Inline Functions</A></H3>
<SPAN class="link_button" id="link-Inline_Functions__button" name="link-Inline_Functions__button"><A href="?showone=Inline_Functions#Inline_Functions">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Inline_Functions')" name="Inline_Functions__button" id="Inline_Functions__button">▶</SPAN>
<DIV style="display:inline;" class="">
As a general rule, put function definitions into the <code>.cxx</code> file and let the compiler decide what gets inlined (it can decide anyway, regardless of the inline keyword).
Use inline when you require the implementation of a function in multiple translation units (e.g. template classes/functions).
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Inline_Functions__body" id="Inline_Functions__body" style="display: none">
<P class="">
<SPAN class="stylepoint_section">Definition: </SPAN>
<p>
The inline keyword indicates that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism.
But a compiler is not required to perform this inline substitution at the point of call.
</p>
<p>
Functions that are defined within a class definition are implicitly inline.
</p>
<p>
An inline function must be defined in every translation unit from where it is called.
It is undefined behavior if the definition of the inline function is not the same for all translation units.
Note that this implies that the function is defined in a header file.
This can have an impact on compile time and lead to longer (= less efficient) development cycles.
</p>
<p>
Note that the inline keyword has no effect on the linkage of a function.
Linkage can be changed via unnamed namespaces or the static keyword.
</p>
</P>
<P class="">
<SPAN class="stylepoint_section">Decision: </SPAN>
<p>
If you add a new function, put it into the <code>.cxx</code> file per default.
Small functions, like accessors and mutators may be placed into the <code>.h</code> file instead (<code>inline</code>).
Also, most template function implementations need to go into the <code>.h</code> file.
If you later determine that a function should be moved from the <code>.cxx</code> file into the <code>.h</code> file, please make sure that it helps the compiler in optimizing the code.
Otherwise you're just increasing compile time.
</p>
</P>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Names_and_Order_of_Includes" id="Names_and_Order_of_Includes">Names and Order of Includes</A></H3>
<SPAN class="link_button" id="link-Names_and_Order_of_Includes__button" name="link-Names_and_Order_of_Includes__button"><A href="?showone=Names_and_Order_of_Includes#Names_and_Order_of_Includes">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Names_and_Order_of_Includes')" name="Names_and_Order_of_Includes__button" id="Names_and_Order_of_Includes__button">▶</SPAN>
<DIV style="display:inline;" class="">
Include headers from external libraries using angle brackets. Include headers from your own project/libraries using double quotes.<br>
Do not rely on implicit includes. Make header files self-sufficient. <br>
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Names_and_Order_of_Includes__body" id="Names_and_Order_of_Includes__body" style="display: none">
<p>
There are two types of #include statements: <code>#include <myFile.h></code> and <code>#include “myFile.h”</code>.
</p>
<ul>
<li> Include headers from external libraries using angle brackets.
<DIV class=""><PRE>#include <iostream>
#include <QtCore/QDate>
#include <zlib.h></PRE></DIV>
</li>
<li>
Include headers from your own project using double quotes.
<DIV class=""><PRE>#include "MyClass.h"</PRE></DIV>
</li>
</ul>
<p>
The header files of external libraries are obviously not in the
same directory as your source files. So you need to use angle brackets.
</p>
<p>
Headers of your own application have a defined relative location to the source
files of your application. Using double quotes, you have to specify the correct
relative path to the include file.
</p>
<i>Include order </i>
<p>
Another important aspect of include management is the include order.
Typically, you have a class named Foo, a file Foo.h and a file Foo.cxx .
The rule is :
In your file Foo.cxx, you should include Foo.h as the first include, before the system
includes.
</p>
<p>
The rationale behind that is to make your header standalone.
</p>
<p>
Let's imagine that your Foo.h looks like this:
<DIV class=""><PRE class="badcode">class Foo
{
public:
Bar getBar();
}</PRE></DIV>
</p>
<p>
And your Foo.cpp looks like this:
<DIV class=""><PRE class="badcode">#include "Bar.h"
#include "Foo.h"</PRE></DIV>
</p>
<p>
Your Foo.cxx file will compile, but it will not compile for other people using Foo.h without including Bar.h.
Including Foo.h first makes sure that your Foo.h header works for others.
<DIV class=""><PRE>// Foo.h
#include "Bar.h"
class Foo
{
public:
Bar getBar();
}
// Foo.cxx
#include "Foo.h"</PRE></DIV>
</p>
<p>
For more details: <a href="https://community.kde.org/Policies/Library_Code_Policy#Getting_.23includes_right">Getting #includes right</a>.
</p>
</DIV></DIV>
</DIV>
</DIV>
<DIV class="">
<H2 name="Namespaces" id="Namespaces">Namespaces</H2>
<p>
Namespaces subdivide the global scope into distinct, named
scopes, and thus are useful for logically grouping related types and functions and
preventing name collisions.
</p>
<DIV class="">
<H3><A name="General_guideline" id="General_guideline">General guideline</A></H3>
<SPAN class="link_button" id="link-General_guideline__button" name="link-General_guideline__button"><A href="?showone=General_guideline#General_guideline">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('General_guideline')" name="General_guideline__button" id="General_guideline__button">▶</SPAN>
<DIV style="display:inline;" class="">
Use a namespace for the project, a second nested namespace for code inside
a sub-project. Use one or two more nested namespaces to logically group types and functions together.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="General_guideline__body" id="General_guideline__body" style="display: none">
<p>
Example of a typical class definition within a project and
sub-project namespace:
</p>
<DIV class=""><PRE>namespace project::subproject
{
class MyClass
{
...
};
} // namespace subproject::project</PRE></DIV>
<p>Alternatively, the C++98/11/14 style for nested namespaces can be used:</p>
<DIV class=""><PRE>namespace project
{
namespace subproject
{
class MyClass
{
...
};
} // namespace subproject
} // namespace project</PRE></DIV>
<p>
A nonmember function that is logically tied to a specific type should be in the
same namespace as that type.
</p>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Using_declarations_and_directives" id="Using_declarations_and_directives">Using declarations and directives</A></H3>
<SPAN class="link_button" id="link-Using_declarations_and_directives__button" name="link-Using_declarations_and_directives__button"><A href="?showone=Using_declarations_and_directives#Using_declarations_and_directives">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Using_declarations_and_directives')" name="Using_declarations_and_directives__button" id="Using_declarations_and_directives__button">▶</SPAN>
<DIV style="display:inline;" class="">
Don't write namespace using declarations or using directives
in a header file or before an #include.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Using_declarations_and_directives__body" id="Using_declarations_and_directives__body" style="display: none">
<p>
<DIV class=""><PRE># include "Bar.h"
// OK in .cxx after include statements
using namespace foo;
// sometimes a using declaration is preferable, to be precise
// about the symbols that get imported
using Foo::Type;</PRE></DIV>
</p>
<p>
<DIV class=""><PRE class="badcode">// Forbidden in .h -- This pollutes the namespace.
using namespace foo;</PRE></DIV>
</p>
<SPAN class="showhide_extrabutton" onclick="javascript:ToggleExtraByName('Using_declarations_and_directives')" name="Using_declarations_and_directives__extra_button" id="Using_declarations_and_directives__extra_button">▶</SPAN><P>
<SPAN class="stylepoint_section">Extra details and exceptions to the rules: </SPAN><div style="display:none;" class="stylepoint_extra" name="Using_declarations_and_directives__extra_body">
The using directive can sometimes be useful in header files to import one namespace into another one.
This can effectively hide a namespace from the public interface, similar to what an inline namespace does.
</div>
</P>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Unnamed_namespaces" id="Unnamed_namespaces">Unnamed namespaces</A></H3>
<SPAN class="link_button" id="link-Unnamed_namespaces__button" name="link-Unnamed_namespaces__button"><A href="?showone=Unnamed_namespaces#Unnamed_namespaces">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Unnamed_namespaces')" name="Unnamed_namespaces__button" id="Unnamed_namespaces__button">▶</SPAN>
<DIV style="display:inline;" class="">
Unnamed namespaces are allowed and even encouraged in
<code>.cxx</code> files, they are not allowed in <code>.h</code>
files.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Unnamed_namespaces__body" id="Unnamed_namespaces__body" style="display: none">
<P class="">
<SPAN class="stylepoint_section">Definition: </SPAN>
All symbols inside an unnamed namespace (sometimes also called anonymous namespace)
will have internal linkage.
Thus, it is impossible to access these objects from other translation units (.cxx files).
</P>
<P class="">
<SPAN class="stylepoint_section">Pros: </SPAN>
Because of the internal linkage it is easier to reason about the code.
This can lead to better optimization from compilers and clearer encapsulation.
</P>
<P class="">
<SPAN class="stylepoint_section">Decision: </SPAN>
Use unnamed namespaces in <code>.cxx</code> files whenever possible.
</P>
<p>
<DIV class=""><PRE>namespace project
{
namespace // This is in a .cxx file.
{
int someFunction(int value) { return value + 1; }
} // unnamed namespace
void someOtherFunction()
{
int value = 0;
value = someFunction(value);
...
}
}</PRE></DIV>
For the above code the compiler can see that <code>someFunction</code> is called from only one place.
It can thus inline the code and drop <code>someFunction</code>.
</p>
<SPAN class="showhide_extrabutton" onclick="javascript:ToggleExtraByName('Unnamed_namespaces')" name="Unnamed_namespaces__extra_button" id="Unnamed_namespaces__extra_button">▶</SPAN><P>
<SPAN class="stylepoint_section">Extra details and exceptions to the rules: </SPAN><div style="display:none;" class="stylepoint_extra" name="Unnamed_namespaces__extra_body">
In some special cases an unnamed namespace can be useful in a header file.
Leave such decisions to architecture designers.
</div>
</P>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Namespace_aliases" id="Namespace_aliases">Namespace aliases</A></H3>
<SPAN class="link_button" id="link-Namespace_aliases__button" name="link-Namespace_aliases__button"><A href="?showone=Namespace_aliases#Namespace_aliases">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Namespace_aliases')" name="Namespace_aliases__button" id="Namespace_aliases__button">▶</SPAN>
<DIV style="display:inline;" class="">
Namespace aliases are allowed anywhere in a <code>.cxx</code> file,
inside the named namespace that wraps an entire <code>.h</code>
file and in functions and methods.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Namespace_aliases__body" id="Namespace_aliases__body" style="display: none">
<p>
<DIV class=""><PRE>// Shorten access to some commonly used names in .cxx 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 pds = ::pipeline_diagnostics::Sidetable;
inline void myInlineFunction() {
// namespace alias local to a function (or method).
namespace fbz = ::foo::bar::baz;
...
}
} // namespace librarian</PRE></DIV>
</p>
<p>
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.
</p>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="std_namespace" id="std_namespace">std namespace</A></H3>
<SPAN class="link_button" id="link-std_namespace__button" name="link-std_namespace__button"><A href="?showone=std_namespace#std_namespace">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('std_namespace')" name="std_namespace__button" id="std_namespace__button">▶</SPAN>
<DIV style="display:inline;" class="">
Do not declare anything in namespace <code>std</code>, not even forward
declarations of standard library classes.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="std_namespace__body" id="std_namespace__body" style="display: none">
<p>
Declaring entities in namespace <code>std</code> represents undefined behavior,
i.e., not portable. To declare entities from the standard library, include
the appropriate header file.
</p>
</DIV></DIV>
</DIV>
</DIV>
<DIV class="">
<H2 name="Scoping" id="Scoping">Scoping</H2>
<DIV class="">
<H3><A name="Nonmember_and_Global_Functions" id="Nonmember_and_Global_Functions">Nonmember and Global Functions</A></H3>
<SPAN class="link_button" id="link-Nonmember_and_Global_Functions__button" name="link-Nonmember_and_Global_Functions__button"><A href="?showone=Nonmember_and_Global_Functions#Nonmember_and_Global_Functions">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Nonmember_and_Global_Functions')" name="Nonmember_and_Global_Functions__button" id="Nonmember_and_Global_Functions__button">▶</SPAN>
<DIV style="display:inline;" class="">
Nonmember functions (also known as global functions) should be
within a namespace.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Nonmember_and_Global_Functions__body" id="Nonmember_and_Global_Functions__body" style="display: none">
<p>Putting nonmember functions in a namespace avoids polluting
the global namespace. Static member functions are an alternative
as long as it makes sense to include the function within the
class.</p>
<DIV class=""><PRE>namespace mynamespace
{
void doGlobalFoo(); // Good -- doGlobalFoo is within a namespace.
class MyClass
{
public:
...
// Good -- doGlobalBar is a static member of class MyClass and
// has a reason to be part of this class (not shown here).
static Bar* doGlobalBar();
}</PRE></DIV>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Local_Variables" id="Local_Variables">Local Variables</A></H3>
<SPAN class="link_button" id="link-Local_Variables__button" name="link-Local_Variables__button"><A href="?showone=Local_Variables#Local_Variables">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Local_Variables')" name="Local_Variables__button" id="Local_Variables__button">▶</SPAN>
<DIV style="display:inline;" class="">
Declare variables as locally as possible.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Local_Variables__body" id="Local_Variables__body" style="display: none">
<p> Variables whose lifetime are longer than necessary have several
drawbacks:
<ul>
<li>They make the code harder to understand and maintain.</li>
<li>They can't be always sensibly initialized.</li>
</ul>
</p>
<SPAN class="showhide_extrabutton" onclick="javascript:ToggleExtraByName('Local_Variables')" name="Local_Variables__extra_button" id="Local_Variables__extra_button">▶</SPAN><P>
<SPAN class="stylepoint_section">Extra details and exceptions to the rules: </SPAN><div style="display:none;" class="stylepoint_extra" name="Local_Variables__extra_body">
<ul>
<li>It can be sometimes more efficient to declare a variable (usually of an
object type) outside a loop.
<p>
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.
</p>
<DIV class=""><PRE class="badcode">// Inefficient implementation:
for (int i = 0; i < bigNumber; ++i) {
Foo foo; // My ctor and dtor get called bigNumber times each.
foo.doSomething(i);
}</PRE></DIV>
<p>
It may be more efficient to declare such a variable used in a
loop outside that loop:
</p>
<DIV class=""><PRE>Foo foo; // My ctor and dtor get called once each.
for (int i = 0; i < bigNumber; ++i) {
foo.doSomething(i);
}</PRE></DIV>
</li>
<li> This item does not apply to constants, because constants don't add a state.
</li>
</ul>
</div>
</P>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Variables_Initialization" id="Variables_Initialization">Variables Initialization</A></H3>
<SPAN class="link_button" id="link-Variables_Initialization__button" name="link-Variables_Initialization__button"><A href="?showone=Variables_Initialization#Variables_Initialization">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Variables_Initialization')" name="Variables_Initialization__button" id="Variables_Initialization__button">▶</SPAN>
<DIV style="display:inline;" class="">
Always initialize variables.<br>
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Variables_Initialization__body" id="Variables_Initialization__body" style="display: none">
<p>
Do not separate initialization from declaration, e.g.
</p>
<DIV class=""><PRE class="badcode">int value;
value = function(); // Bad -- initialization separate from declaration.</PRE></DIV>
<DIV class=""><PRE>int value = function(); // Good -- declaration has initialization.</PRE></DIV>
<p>
Use a default initial value or ? to reduce mixing data flow with control
flow.
</p>
<DIV class=""><PRE class="badcode">int speedupFactor; // Bad: does not initialize variable
if (condition) {
speedupFactor = NoFactor;
}
else {
speedupFactor = DoubleFactor;
}</PRE></DIV>
<DIV class=""><PRE>int speedupFactor = DoubleFactor; // Good: initializes variable
if (condition) {
speedupFactor = NoFactor;
}</PRE></DIV>
<DIV class=""><PRE>int speedupFactor = condition ? NoFactor : DoubleFactor; // Good: initializes variable</PRE></DIV>
<p>
Prefer declaration of loop variables inside a loop, e.g.
</p>
<DIV class=""><PRE class="badcode">int i; // Bad: does not initialize variable
for (i = 0; i < number; ++i) {
doSomething(i);
}</PRE></DIV>
<DIV class=""><PRE>for (int i = 0; i < number; ++i) {
doSomething(i); // Good
}</PRE></DIV>
</DIV></DIV>
</DIV>
<DIV class="">
<SPAN class="cpp11_marker">since C++11</SPAN><H3><A name="Brace_Initialization" id="Brace_Initialization">Brace Initialization</A></H3>
<SPAN class="link_button" id="link-Brace_Initialization__button" name="link-Brace_Initialization__button"><A href="?showone=Brace_Initialization#Brace_Initialization">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Brace_Initialization')" name="Brace_Initialization__button" id="Brace_Initialization__button">▶</SPAN>
<DIV style="display:inline;" class="">
Prefer initialization with braces except for single-argument assignment.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Brace_Initialization__body" id="Brace_Initialization__body" style="display: none">
<p>In C++11, the brace initialization syntax for builtin arrays and POD structures has been extended for use with all other datatypes.
<p> Example of brace initialization:
</p>
<DIV class=""><PRE>std::vector<std::string> myVector{"alpha", "beta", "gamma"};</PRE></DIV>
</p>
<p>
Example of single-argument assignments:
</p>
<DIV class=""><PRE>int value = 3; // preferred style
std::string name = "Some Name";
int value { 3 }; // also possible
std::string name{ "Some Name" };
std::string name = { "Some Name" };</PRE></DIV>
<p>User data types can also define constructors that take
<code>initializer_list</code>, which is automatically created from
<i>braced-init-list</i>:
<DIV class=""><PRE>#include <initializer_list>
class MyType
{
public:
// initializer_list is a reference to the underlying init list,
// so it can be passed by value.
MyType(std::initializer_list<int> initList) {
for (int element : initList) { .. }
}
};
MyType myObject{2, 3, 5, 7};</PRE></DIV></p>
<p>Finally, brace initialization can also call ordinary constructors of
data types that do not have <code>initializer_list</code> constructors.
<DIV class=""><PRE>// Calls ordinary constructor as long as MyOtherType has no
// initializer_list constructor.
class MyOtherType
{
public:
explicit MyOtherType(std::string name);
MyOtherType(int value, std::string name);
};
MyOtherType object1 = {1, "b"};
// If the constructor is explicit, you can't use the "= {}" form.
MyOtherType object2{"b"};</PRE></DIV></p>
<p>Never assign a <i>braced-init-list</i> to an auto local variable. In the
single element case, what this means can be confusing.
<DIV class=""><PRE class="badcode">auto value = {1.23}; // value is an initializer_list<double></PRE></DIV>
<DIV class=""><PRE>auto value = double{1.23}; // Good -- value is a double, not an initializer_list.</PRE></DIV>
</p>
<p> For clarity of the examples above we use directly explicit values, however following
the rule about <a href="#Magic_Numbers">magic numbers</a> requires to define all such
numbers as named constants or <code>constexpr</code> first. </p>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Global_Variables" id="Global_Variables">Global Variables</A></H3>
<SPAN class="link_button" id="link-Global_Variables__button" name="link-Global_Variables__button"><A href="?showone=Global_Variables#Global_Variables">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Global_Variables')" name="Global_Variables__button" id="Global_Variables__button">▶</SPAN>
<DIV style="display:inline;" class="">
Variables declared in the global scope are not allowed. Other global variables, including
static class variables and variables in namespace scope, should be
avoided where other means of communication are possible.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Global_Variables__body" id="Global_Variables__body" style="display: none">
<P class="">
<SPAN class="stylepoint_section">Definition: </SPAN>
A global variable is a variable that can be accessed (theoretically) from everywhere in the program.
The adjective "global" should rather be understood as concerning its linkage, not whether it is in the global scope.
<DIV class=""><PRE class="badcode">int gBar; // this is obviously global
class Something
{
private:
static int sId; // but this one too (details at the end of the rule)
};
namespace notglobalscope
{
Foo fooObject; // and finally this one as well
}</PRE></DIV>
</P>
<P class="">
<SPAN class="stylepoint_section">Pros: </SPAN>
Global variables are a simple solution to sharing of data.
</P>
<P class="">
<SPAN class="stylepoint_section">Cons: </SPAN>
Global variables make it harder to reason about the code (for humans and compilers):
the smaller the number of variables a given region of code reads and writes, the easier.
Global variables can be read and written from anywhere.
Therefore, global variables pose a challenge to the optimizer.
</P>
<P class="">
<SPAN class="stylepoint_section">Decision: </SPAN>
We want to reduce the shared data in our software to the unavoidable minimum.
Therefore, global variables should be avoided where other means of communication are possible.
</P>
<SPAN class="showhide_extrabutton" onclick="javascript:ToggleExtraByName('Global_Variables')" name="Global_Variables__extra_button" id="Global_Variables__extra_button">▶</SPAN><P>
<SPAN class="stylepoint_section">Extra details and exceptions to the rules: </SPAN><div style="display:none;" class="stylepoint_extra" name="Global_Variables__extra_body">
Note that a private static class variable sId is global. For example two threads having
each an instance of the class could access sId via these instances.
</div>
</P>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Global_variables_initialization" id="Global_variables_initialization">Global variables initialization</A></H3>
<SPAN class="link_button" id="link-Global_variables_initialization__button" name="link-Global_variables_initialization__button"><A href="?showone=Global_variables_initialization#Global_variables_initialization">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Global_variables_initialization')" name="Global_variables_initialization__button" id="Global_variables_initialization__button">▶</SPAN>
<DIV style="display:inline;" class="">
In the rare and justified cases where you use global variables, including file-static variables, static member variables and variables in
namespace scope, initialize them statically.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Global_variables_initialization__body" id="Global_variables_initialization__body" style="display: none">
<P class="">
<SPAN class="stylepoint_section">Definition: </SPAN>
<ul>
<li>This rule additionally applies to file-static variables.</li>