forked from evgenykislov/styleguide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcppguide_ru.html
5573 lines (4426 loc) · 273 KB
/
cppguide_ru.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Руководство Google по стилю в C++</title>
<link rel="stylesheet" href="include/styleguide_ru.css" />
<script src="include/styleguide_ru.js"></script>
<link rel="shortcut icon" href="https://www.google.com/favicon.ico" />
</head>
<body onload="initStyleGuide();">
<div id="content">
<h1>Руководство Google по стилю в C++</h1>
<div class="horizontal_toc" id="tocDiv"></div>
<div class="main_body">
<h2 id="Background" class="ignoreLink">Вступление</h2>
<p>C++ один из основных языков программирования, используемый в open-source проектах Google.
Известно, что C++ очень мощный язык. Вместе с тем это сложный язык и, при неправильном использовании,
может быть рассадником багов, затруднить чтение и поддержку кода.</p>
<p>Цель руководства - управлять сложностью кода,
описывая в деталях как стоит (или не стоит) писать код на C++.
Правила этого руководства упростят управление кодом и увеличат продуктивность кодеров.</p>
<p><em>Style / Стиль</em> - соглашения, которым следует C++ код.
Стиль - это больше, чем форматирование файла с кодом.</p>
<p>Большинство open-source проектов, разрабатываемых Google, соответствуют этому руководству.</p>
<p>Примечание: это руководство не является учебником по C++:
предполагается, что вы знакомы с языком.</p>
<h3 id="Goals">Цели Руководства по стилю</h3>
<p>Зачем нужен этот документ?</p>
<p>Есть несколько основных целей этого документа, внутренних
<b>Зачем</b>, лежащих в основе отдельных правил.
Используя эти цели можно избежать длинных дискуссий: почему правила такие и зачем им следовать.
Если вы понимаете цели каждого правила, то вам легче с ними согласиться или отвергнуть,
оценить альтернативы при изменении правил под себя.</p>
<p>Цели руководства следующие::</p>
<dl>
<dt>Правила должны стоить изменений</dt>
<dd>Преимущества от использования единого стиля должны перевешивать
недовольство инженеров по запоминанию и использованию правил.
Преимущество оценивается по сравнению с кодовой базой без применения правил,
поэтому если ваши люди всё равно не будут применять правила,
то выгода будет очень небольшой.
Этот принцип объясняет почему некоторые правила отсутствуют:
например, <code>goto</code> нарушает многие принципы, однако он практически не используется,
поэтому Руководство это не описывает.</dd>
<dt>Оптимизировано для чтения, не для написания</dt>
<dd>Наша кодовая база (и большинство отдельных компонентов из неё)
будет использоваться продолжительное время. Поэтому, на чтение этого кода
будет тратиться существенно больше времени, чем на написание.
Мы явно заботимся чтобы нашим инженерам было лего читать, поддерживать,
отлаживать код. "Оставляй отладочный/логирующий код" - одно из следствий:
когда кусок кода работает "странно" (например, при передаче владения указателем),
наличие текстовых подсказок может быть очень полезным (<code>std::unique_ptr</code>
явно показывает передачу владения). </dd>
<dt>Пиши код, похожий на существующий</dt>
<dd>Использование единого стиля на кодовой базе позволяет переключиться на другие, более важные, вопросы.
Также, единый стиль способствует автоматизации. И, конечно, автоформат кода
(или выравнивание <code>#include</code>-ов) работает правильно, если он
соответствует требованиям утилиты. В остальных случаях из набора правил
применяется только одно (наиболее подходящее), а некоторая гибкость в
использовании правил позволяет людям меньше спорить.</dd>
<dt>Пиши код, похожий на используемый в C++ сообщества (по возможности)</dt>
<dd>Согласованность нашего кода с C++ кодом других организаций и сообществ
весьма полезна. Если возможности стандартного C++ или принятые идиомы языка
облегчают написание программ, это повод использовать их. Однако,
иногда стандарт и идиомы плохо подходят для задачи. В этих случаях
(как описано ниже) имеет смысл ограничить или запретить использование
некоторых стандартных возможностей. В некоторых случаях создаётся свой решение,
но иногда используются внешние библиотеки (вместо стандартной библиотеки C++)
и переписывание её под свой стандарт слишком затратно.</dd>
<dt>Избегайте неожиданных или опасных конструкций</dt>
<dd>В языке C++ есть неочевидные и даже опасные подходы. Некоторые
стили кодирования ограничивают их использование, т.к. их использование
несёт большие риски для правильности кода.</dd>
<dt>Избегайте конструкций, которые средний C++ программист считает заумными
и сложно поддерживаемыми</dt>
<dd>В C++ есть возможности, которые в целом не приветствуются по причине
усложнения кода. Однако, в часто используемом коде применение хитрых
конструкций более оправданно благодаря многократному использованию,
также новые порции кода станут более понятны.
В случае сомнений - проконсультируйтесь с лидером проекта.
Это очень важно для нашей кодовой базы, т.к. владельцы кода и команда поддержки
меняются со временем: даже если сейчас все понимают код,
через несколько лет всё может исзмениться.</dd>
<dt>Учитывайте масштаб кода</dt>
<dd>С кодовой базой более 100 миллионов строк и тысячами инженеров,
ошибки и упрощения могут дорого обойтись. Например, важно избегать
замусоривания глобального пространства имён: коллизии имён очень
сложно избежать в большой базе кода если всё объявляется в глобальном
пространстве имён.</dd>
<dt>Оптимизируйте по необходимости</dt>
<dd>Оптимизация производительности иногда важнее, чем следование правилам в кодировании.</dd>
</dl>
<p>Намерение этого документа - обеспечить максимально понятное руководство
при разумных ограничениях. Как всегда, здравый смысл никто не отменял.
Этой спецификацией мы хотим установить соглашения для всего сообщества Google в C++,
не только для отдельных команд или людей. Относитесь со скепсисом к хитрым или
необычным конструкциям: отсутствие ограничения не всегда есть разрешение.
И, если не можешь решить сам, спроси начальника.</p>
<h2 id="C++_Version">Версия C++</h2>
<p>Сейчас код должен соответствовать C++17, т.е. возможности C++2x нежелательны.
В дальнейшем, руководство будет корректироваться на более новые версии C++.</p>
<p>Не используйте
<a href="#Nonstandard_Extensions">нестандартные расширения</a>.</p>
<p>Учитывайте совместимость с другим окружением, если собираетесь
использовать C++14 and C++17 в своём проекте.</p>
<h2 id="Header_Files">Заголовочные файлы</h2>
<p>Желательно, чтобы каждый <code>.cc</code> файл исходного кода
имел парный <code>.h</code> заголовочный файл. Также есть известные
исключения из этого правила, такие как юниттесты или небольшие
<code>.cc</code> файлы, содержащие только функцию <code>main()</code>.</p>
<p>Правильное использование заголовочных файлов может оказать
огромное влияние на читабельность, размер и производительность вашего кода.</p>
<p>Следующие правила позволят избежать частых проблем с заголовочными файлами.</p>
<h3 id="Self_contained_Headers">Независимые заголовочные файлы</h3>
<p>Заголовочные файлы должны быть самодостаточными (в плане компиляции)
и иметь расширение <code>.h</code>. Другие файлы (не заголовочные), предназначенные
для включения в код, должны быть с расширением <code>.inc</code> и использоваться
в паре с включающим кодом.</p>
<p>Все заголовочные файлы должны быть самодостаточыми. Пользователи и инструменты разработки не
должны зависеть от специальных зависимостей при использовании заголовочного файла.
Заголовочный файл должен иметь <a href="#The__define_Guard">блокировку от повторного включения</a> и
включать все необходимые файлы.</p>
<p>Предпочтительно размещать определения для шаблонов и inline-функций
в одном файле с их декларациями. И эти определения должны быть
включены (include) в каждый <code>.cc</code> файл, использующий их, иначе
могут быть ошибки линковки на некоторых конфигурациях сборки. Если же
декларации и определения находятся в разных файлах, включение одного должно
подключать другой. Не выделяйте определения в отдельные заголовочные файлы
(<code>-inl.h</code>). Раньше такая практика была очень популярна, сейчас
это нежелательно.</p>
<p>Как исключение, если из шаблона создаются все доступные варианты
шаблонных аргументов или если шаблон реализует функционал, используемый
только одним классом - тогда допустимо определять шаблон в одном
(и только одном) <code>.cc</code> файле, в котором этот шаблон и используется.</p>
<p>Возможны редкие ситуации, когда заголовочный файл не самодостаточный.
Это может происходить, когда файл подключается в нестандартном месте,
например в середине другого файла. В этом случае может отсутствовать
<a href="#The__define_Guard">блокировка от повторного включения</a>, и
дополнительные заголовочные файлы также могут не подключаться.
Именуйте такие файлы расширением <code>.inc</code>. Используйте их парой и
старайтесь чтобы они максимально соответствовали общим требованиям.</p>
<h3 id="The__define_Guard">Блокировка от повторного включения</h3>
<p>Все заголовочные файлы должны быть с защитой от повторного включения посредством
<code>#define</code>. Формат макроопределения должен быть:
<code><i><PROJECT></i>_<i><PATH></i>_<i><FILE></i>_H_</code>.</p>
<div>
<p>Для гарантии уникальности, используйте компоненты полного пути к файлу в дереве проекта.
Например, файл <code>foo/src/bar/baz.h</code> в проекте <code>foo</code> может иметь следующую блокировку:</p>
</div>
<pre>#ifndef FOO_BAR_BAZ_H_
#define FOO_BAR_BAZ_H_
...
#endif // FOO_BAR_BAZ_H_
</pre>
<h3 id="Forward_Declarations">Предварительное объявление</h3>
<p>По возможности, не используйте предварительное объявление.
Вместо этого делайте <code>#include</code> необходимых заголовочных файлов.</p>
<p class="definition"></p>
<p>"Предварительное объявление" - декларация класса, функции, шаблона без
соответствующего определения.</p>
<p class="pros"></p>
<ul>
<li>Предварительной объявление может уменьшить время компиляции.
Использование <code>#include</code> требует от компилятора сразу
открывать (и обрабатывать) больше файлов.</li>
<li>Предварительное объявление позволит избежать ненужной
перекомпиляции. Применение <code>#include</code> может привести к
частой перекомпиляции из-за различных изменений в заголовочных файлах.</li>
</ul>
<p class="cons"></p>
<ul>
<li>Предварительное объявление может скрывать от перекомпиляции
зависимости, которые изменились.</li>
<li>При изменении API, предварительное объявление может стать некорректным.
Как результат, предварительное объявление функция или шаблонов может блокировать
изменение API: замена типов параметров на похожий, добавление параметров
по умолчанию в шаблон, перенос в новое пространство имён.</li>
<li>Предварительное объявление символов из <code>std::</code> может вызвать
неопределённое поведение.</li>
<li>Иногда тяжело понять, что лучше подходит: предварительное объявление или
обычный <code>#include</code>.
Однако, замена <code>#include</code> на предварительное объявление может (без предупреждений) поменять
смысл кода:
<pre> // b.h:
struct B {};
struct D : B {};
// good_user.cc:
#include "b.h"
void f(B*);
void f(void*);
void test(D* x) { f(x); } // calls f(B*)
</pre>
Если в коде заменить <code>#include</code> на предварительное объявление
для структур <code>B</code> и <code>D</code>, то
<code>test()</code> будет вызывать <code>f(void*)</code>.
</li>
<li>Предварительное объявление множества сущностей может быть
чересчур объёмным, и может быть проще подключить заголовочный файл.</li>
<li>Структура кода, допускающая предварительное объявление
(и, далее, использование указателей в качестве членов класса)
может сделать код запутанным и медленным.</li>
</ul>
<p class="decision"></p>
<ul>
<li>Старайтесь избегать предварительного объявления сущностей,
объявленных в другом проекте.</li>
<li>Когда используйте функцию, объявленную в заголовочном файле,
всегда <code>#include</code> этот файл.</li>
<li>Когда используйте шаблон класса, предпочтительно
<code>#include</code> его заголовочный файл.</li>
</ul>
<p>Также смотри правила включения в <a href="#Names_and_Order_of_Includes">Имена и Порядок включения (include)</a>.</p>
<h3 id="Inline_Functions">Встраиваемые (inline) функции</h3>
<p>Определяйте функции как встраиваемые только когда они маленькие,
например не более 10 строк.</p>
<p class="definition"></p>
<p>Вы можете объявлять функции встраиваемыми и указать компилятору на возможность
включать её напрямую в вызывающий код, помимо стандартного способа с вызовом функции.</p>
<p class="pros"></p>
<p>Использование встраиваемых функций может генерировать более эффективный код,
особенно когда функции маленькие. Используйте эту возможность для get/set функций,
других коротких и критичных для производительности функций.</p>
<p class="cons"></p>
<p>Чрезмерное использование встраиваемых функций может сделать программу медленнее.
Также встраиваемые функции, в зависимости от размера её, могут как увеличить, так и уменьшить
размер кода. Если это маленькие функции, то код может быть уменьшен.
Если же функция большая, то размер кода может очень сильно вырасти.
Учтите, что на современных процессорах более компактный код выполняется быстрее
благодаря лучшему использованию кэша инструкций.</p>
<p class="decision"></p>
<p>Хорошим правилом будет не делать функции встраиваемыми, если они превышают
10 строк кода. Избегайте делать встраиваемыми деструкторы, т.к. они неявно
могут содержать много дополнительного кода: вызовы деструкторов переменных и
базовых классов!</p>
<p>Ещё одно хорошее правило: обычно нет смысла делать встраиваемыми функции,
в которых есть циклы или операции switch (кроме вырожденных случаев, когда цикл
или другие операторы никогда не выполняются).</p>
<p>Важно понимать, что встраиваемая функция не обязательно будет скомпилирована
в код именно так. Например, обычно виртуальные и рекурсивные функции компилируются
со стандартным вызовом. Вообще, рекурсивные функции не должны объявляться встраиваемыми.
Основная же причина делать встраиваемые виртуальные функции - разместить определение (код)
в самом определении класса (для документирования поведения или удобства чтения) - часто
используется для get/set функций.</p>
<h3 id="Names_and_Order_of_Includes">Имена и Порядок включения (include)</h3>
<p>Вставляйте заголовочные файлы в следующем порядке:
парный файл (например, foo.h - foo.cc), системные файлы C, стандартная библиотека C++,
другие библиотеки, файлы вашего проекта.</p>
<p>
Все заголовочные файлы проекта должны указываться относительно
директории исходных файлов проекта без использования таких UNIX псевдонимов
как <code>.</code> (текущая директория) или <code>..</code>
(родительская директория). Например,
<code>google-awesome-project/src/base/logging.h</code>
должен включаться так:</p>
<pre>#include "base/logging.h"
</pre>
<p>Другой пример: если основная функция файлов <code><var>dir/foo</var>.cc</code> и
<code><var>dir/foo_test</var>.cc</code>
это реализация и тестирование кода, объявленного в
<code><var>dir2/foo2</var>.h</code>, то записывайте заголовочные файлы
в следующем порядке:</p>
<ol>
<li><code><var>dir2/foo2</var>.h</code>.</li>
<li>------ Пустая строка</li>
<li>Системные заголовочные файлы C (точнее: файлы с включением угловыми скобками
с расширением <code>.h</code>), например <code><unistd.h></code>,
<code><stdlib.h></code>.</li>
<li>------ Пустая строка</li>
<li>Заголовочные файлы стандартной библиотеки C++ (без расширения в файлах), например
<code><algorithm></code>, <code><cstddef></code>.</li>
<li>------ Пустая строка</li>
<li>Заголовочные <code>.h</code> файлы других библиотек.</li>
<li>Файлы <code>.h</code> вашего проекта.</li>
</ol>
<p>Отделяйте каждую (непустую) группу файлов пустой строкой.</p>
<p>Такой порядок файлов позволяет выявить ошибки, когда
в парном заголовочном файле (<code><var>dir2/foo2</var>.h</code>)
пропущены необходимые заголовочные файлы (системные и др.) и
сборка соответствующих файлов <code><var>dir/foo</var>.cc</code>
или <code><var>dir/foo</var>_test.cc</code> завершится ошибкой.
Как результат, ошибка сразу же появится у разработчика,
работающего с этими файлами (а не у другой команды,
которая только использует внешнюю библиотеку).</p>
<p>Обычно парные файлы <code><var>dir/foo</var>.cc</code> и
<code><var>dir2/foo2</var>.h</code> находятся в одной директории
(например, <code>base/basictypes_test.cc</code> и
<code>base/basictypes.h</code>), хотя это не обязательно.</p>
<p>Учтите, что заголовочные файлы C, такие как <code>stddef.h</code>
обычно взаимозаменяемы соответствующими файлами C++ (<code>cstddef</code>).
Можно использовать любой вариант, но лучше следовать стилю
существующего кода.</p>
<p>Внутри каждой секции заголовочные файлы лучше всего перечислять в алфавитном порядке.
Учтите, что ранее написанный код может не следовать этому правилу. По возможности
(например, при исправлениях в файле), исправляйте порядок файлов на правильный.</p>
<p>Следует включать все заголовочные файлы, которые объявляют требуемые вам типы,
за исключением случаев <a href="#Forward_Declarations">предварительного объявления</a>.
Если ваш код использует типы из <code>bar.h</code>, не полагайтесь на то, что
другой файл <code>foo.h</code> включает <code>bar.h</code> и вы можете ограничиться включением только <code>foo.h</code>:
включайте явно <code>bar.h</code> (кроме случаев, когда явно указано (возможно, в документации),
что <code>foo.h</code> также выдаст вам типы из <code>bar.h</code>).</p>
<p>Например, список заголовочных файлов в
<code>google-awesome-project/src/foo/internal/fooserver.cc</code>
может выглядеть так:</p>
<pre>#include "foo/server/fooserver.h"
#include <sys/types.h>
#include <unistd.h>
#include <string>
#include <vector>
#include "base/basictypes.h"
#include "base/commandlineflags.h"
#include "foo/server/bar.h"
</pre>
<p><b>Исключения:</b></p>
<p>Бывают случаи, когда требуется включение заголовочных файлов в зависимости
от условий препроцессора (например, в зависимости от используемой ОС).
Такое включение старайтесь делать как можно короче (локализованно) и размещать после
других заголовочных файлов. Например:</p>
<pre>#include "foo/public/fooserver.h"
#include "base/port.h" // For LANG_CXX11.
#ifdef LANG_CXX11
#include <initializer_list>
#endif // LANG_CXX11
</pre>
<h2 id="Scoping">Scoping</h2>
<h3 id="Namespaces">Namespaces</h3>
<p>With few exceptions, place code in a namespace. Namespaces
should have unique names based on the project name, and possibly
its path. Do not use <i>using-directives</i> (e.g.
<code>using namespace foo</code>). Do not use
inline namespaces. For unnamed namespaces, see
<a href="#Unnamed_Namespaces_and_Static_Variables">Unnamed Namespaces and
Static Variables</a>.
</p><p class="definition"></p>
<p>Namespaces subdivide the global scope
into distinct, named scopes, and so are useful for preventing
name collisions in the global scope.</p>
<p class="pros"></p>
<p>Namespaces provide a method for preventing name conflicts
in large programs while allowing most code to use reasonably
short names.</p>
<p>For example, if two different projects have a class
<code>Foo</code> in the global scope, these symbols may
collide at compile time or at runtime. If each project
places their code in a namespace, <code>project1::Foo</code>
and <code>project2::Foo</code> are now distinct symbols that
do not collide, and code within each project's namespace
can continue to refer to <code>Foo</code> without the prefix.</p>
<p>Inline namespaces automatically place their names in
the enclosing scope. Consider the following snippet, for
example:</p>
<pre class="neutralcode">namespace outer {
inline namespace inner {
void foo();
} // namespace inner
} // namespace outer
</pre>
<p>The expressions <code>outer::inner::foo()</code> and
<code>outer::foo()</code> are interchangeable. Inline
namespaces are primarily intended for ABI compatibility
across versions.</p>
<p class="cons"></p>
<p>Namespaces can be confusing, because they complicate
the mechanics of figuring out what definition a name refers
to.</p>
<p>Inline namespaces, in particular, can be confusing
because names aren't actually restricted to the namespace
where they are declared. They are only useful as part of
some larger versioning policy.</p>
<p>In some contexts, it's necessary to repeatedly refer to
symbols by their fully-qualified names. For deeply-nested
namespaces, this can add a lot of clutter.</p>
<p class="decision"></p>
<p>Namespaces should be used as follows:</p>
<ul>
<li>Follow the rules on <a href="#Namespace_Names">Namespace Names</a>.
</li><li>Terminate namespaces with comments as shown in the given examples.
</li><li>
<p>Namespaces wrap the entire source file after
includes,
<a href="https://gflags.github.io/gflags/">
gflags</a> definitions/declarations
and forward declarations of classes from other namespaces.</p>
<pre>// In the .h file
namespace mynamespace {
// All declarations are within the namespace scope.
// Notice the lack of indentation.
class MyClass {
public:
...
void Foo();
};
} // namespace mynamespace
</pre>
<pre>// In the .cc file
namespace mynamespace {
// Definition of functions is within scope of the namespace.
void MyClass::Foo() {
...
}
} // namespace mynamespace
</pre>
<p>More complex <code>.cc</code> files might have additional details,
like flags or using-declarations.</p>
<pre>#include "a.h"
ABSL_FLAG(bool, someflag, false, "dummy flag");
namespace mynamespace {
using ::foo::Bar;
...code for mynamespace... // Code goes against the left margin.
} // namespace mynamespace
</pre>
</li>
<li>To place generated protocol
message code in a namespace, use the
<code>package</code> specifier in the
<code>.proto</code> file. See
<a href="https://developers.google.com/protocol-buffers/docs/reference/cpp-generated#package">
Protocol Buffer Packages</a>
for details.</li>
<li>Do not declare anything in namespace
<code>std</code>, including forward declarations of
standard library classes. Declaring entities in
namespace <code>std</code> is undefined behavior, i.e.,
not portable. To declare entities from the standard
library, include the appropriate header file.</li>
<li><p>You may not use a <i>using-directive</i>
to make all names from a namespace available.</p>
<pre class="badcode">// Forbidden -- This pollutes the namespace.
using namespace foo;
</pre>
</li>
<li><p>Do not use <i>Namespace aliases</i> at namespace scope
in header files except in explicitly marked
internal-only namespaces, because anything imported into a namespace
in a header file becomes part of the public
API exported by that file.</p>
<pre>// Shorten access to some commonly used names in .cc files.
namespace baz = ::foo::bar::baz;
</pre>
<pre>// Shorten access to some commonly used names (in a .h file).
namespace librarian {
namespace impl { // Internal, not part of the API.
namespace sidetable = ::pipeline_diagnostics::sidetable;
} // namespace impl
inline void my_inline_function() {
// namespace alias local to a function (or method).
namespace baz = ::foo::bar::baz;
...
}
} // namespace librarian
</pre>
</li><li>Do not use inline namespaces.</li>
</ul>
<h3 id="Unnamed_Namespaces_and_Static_Variables">Unnamed Namespaces and Static
Variables</h3>
<p>When definitions in a <code>.cc</code> file do not need to be
referenced outside that file, place them in an unnamed
namespace or declare them <code>static</code>. Do not use either
of these constructs in <code>.h</code> files.
</p><p class="definition"></p>
<p>All declarations can be given internal linkage by placing them in unnamed
namespaces. Functions and variables can also be given internal linkage by
declaring them <code>static</code>. This means that anything you're declaring
can't be accessed from another file. If a different file declares something with
the same name, then the two entities are completely independent.</p>
<p class="decision"></p>
<p>Use of internal linkage in <code>.cc</code> files is encouraged
for all code that does not need to be referenced elsewhere.
Do not use internal linkage in <code>.h</code> files.</p>
<p>Format unnamed namespaces like named namespaces. In the
terminating comment, leave the namespace name empty:</p>
<pre>namespace {
...
} // namespace
</pre>
<h3 id="Nonmember,_Static_Member,_and_Global_Functions">Nonmember, Static Member, and Global Functions</h3>
<p>Prefer placing nonmember functions in a namespace; use completely global
functions rarely. Do not use a class simply to group static functions. Static
methods of a class should generally be closely related to instances of the
class or the class's static data.</p>
<p class="pros"></p>
<p>Nonmember and static member functions can be useful in
some situations. Putting nonmember functions in a
namespace avoids polluting the global namespace.</p>
<p class="cons"></p>
<p>Nonmember and static member functions may make more sense
as members of a new class, especially if they access
external resources or have significant dependencies.</p>
<p class="decision"></p>
<p>Sometimes it is useful to define a
function not bound to a class instance. Such a function
can be either a static member or a nonmember function.
Nonmember functions should not depend on external
variables, and should nearly always exist in a namespace.
Do not create classes only to group static member functions;
this is no different than just giving the function names a
common prefix, and such grouping is usually unnecessary anyway.</p>
<p>If you define a nonmember function and it is only
needed in its <code>.cc</code> file, use
<a href="#Unnamed_Namespaces_and_Static_Variables">internal linkage</a> to limit
its scope.</p>
<h3 id="Local_Variables">Local Variables</h3>
<p>Place a function's variables in the narrowest scope
possible, and initialize variables in the declaration.</p>
<p>C++ allows you to declare variables anywhere in a
function. We encourage you to declare them in as local a
scope as possible, and as close to the first use as
possible. This makes it easier for the reader to find the
declaration and see what type the variable is and what it
was initialized to. In particular, initialization should
be used instead of declaration and assignment, e.g.:</p>
<pre class="badcode">int i;
i = f(); // Bad -- initialization separate from declaration.
</pre>
<pre>int j = g(); // Good -- declaration has initialization.
</pre>
<pre class="badcode">std::vector<int> v;
v.push_back(1); // Prefer initializing using brace initialization.
v.push_back(2);
</pre>
<pre>std::vector<int> v = {1, 2}; // Good -- v starts initialized.
</pre>
<p>Variables needed for <code>if</code>, <code>while</code>
and <code>for</code> statements should normally be declared
within those statements, so that such variables are confined
to those scopes. E.g.:</p>
<pre>while (const char* p = strchr(str, '/')) str = p + 1;
</pre>
<p>There is one caveat: 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>
<pre class="badcode">// Inefficient implementation:
for (int i = 0; i < 1000000; ++i) {
Foo f; // My ctor and dtor get called 1000000 times each.
f.DoSomething(i);
}
</pre>
<p>It may be more efficient to declare such a variable
used in a loop outside that loop:</p>
<pre>Foo f; // My ctor and dtor get called once each.
for (int i = 0; i < 1000000; ++i) {
f.DoSomething(i);
}
</pre>
<h3 id="Static_and_Global_Variables">Static and Global Variables</h3>
<p>Objects with
<a href="http://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration">
static storage duration</a> are forbidden unless they are
<a href="http://en.cppreference.com/w/cpp/types/is_destructible">trivially
destructible</a>. Informally this means that the destructor does not do
anything, even taking member and base destructors into account. More formally it
means that the type has no user-defined or virtual destructor and that all bases
and non-static members are trivially destructible.
Static function-local variables may use dynamic initialization.
Use of dynamic initialization for static class member variables or variables at
namespace scope is discouraged, but allowed in limited circumstances; see below
for details.</p>
<p>As a rule of thumb: a global variable satisfies these requirements if its
declaration, considered in isolation, could be <code>constexpr</code>.</p>
<p class="definition"></p>
<p>Every object has a <dfn>storage duration</dfn>, which correlates with its
lifetime. Objects with static storage duration live from the point of their
initialization until the end of the program. Such objects appear as variables at
namespace scope ("global variables"), as static data members of classes, or as
function-local variables that are declared with the <code>static</code>
specifier. Function-local static variables are initialized when control first
passes through their declaration; all other objects with static storage duration
are initialized as part of program start-up. All objects with static storage
duration are destroyed at program exit (which happens before unjoined threads
are terminated).</p>
<p>Initialization may be <dfn>dynamic</dfn>, which means that something
non-trivial happens during initialization. (For example, consider a constructor
that allocates memory, or a variable that is initialized with the current
process ID.) The other kind of initialization is <dfn>static</dfn>
initialization. The two aren't quite opposites, though: static
initialization <em>always</em> happens to objects with static storage duration
(initializing the object either to a given constant or to a representation
consisting of all bytes set to zero), whereas dynamic initialization happens
after that, if required.</p>
<p class="pros"></p>
<p>Global and static variables are very useful for a large number of
applications: named constants, auxiliary data structures internal to some
translation unit, command-line flags, logging, registration mechanisms,
background infrastructure, etc.</p>
<p class="cons"></p>
<p>Global and static variables that use dynamic initialization or have
non-trivial destructors create complexity that can easily lead to hard-to-find
bugs. Dynamic initialization is not ordered across translation units, and
neither is destruction (except that destruction
happens in reverse order of initialization). When one initialization refers to
another variable with static storage duration, it is possible that this causes
an object to be accessed before its lifetime has begun (or after its lifetime
has ended). Moreover, when a program starts threads that are not joined at exit,
those threads may attempt to access objects after their lifetime has ended if
their destructor has already run.</p>
<p class="decision"></p>
<h4>Decision on destruction</h4>
<p>When destructors are trivial, their execution is not subject to ordering at
all (they are effectively not "run"); otherwise we are exposed to the risk of
accessing objects after the end of their lifetime. Therefore, we only allow
objects with static storage duration if they are trivially destructible.
Fundamental types (like pointers and <code>int</code>) are trivially
destructible, as are arrays of trivially destructible types. Note that
variables marked with <code>constexpr</code> are trivially destructible.</p>
<pre>const int kNum = 10; // allowed
struct X { int n; };
const X kX[] = {{1}, {2}, {3}}; // allowed
void foo() {
static const char* const kMessages[] = {"hello", "world"}; // allowed
}
// allowed: constexpr guarantees trivial destructor
constexpr std::array<int, 3> kArray = {{1, 2, 3}};</pre>
<pre class="badcode">// bad: non-trivial destructor
const std::string kFoo = "foo";
// bad for the same reason, even though kBar is a reference (the
// rule also applies to lifetime-extended temporary objects)
const std::string& kBar = StrCat("a", "b", "c");
void bar() {
// bad: non-trivial destructor
static std::map<int, int> kData = {{1, 0}, {2, 0}, {3, 0}};
}</pre>
<p>Note that references are not objects, and thus they are not subject to the
constraints on destructibility. The constraint on dynamic initialization still
applies, though. In particular, a function-local static reference of the form
<code>static T& t = *new T;</code> is allowed.</p>
<h4>Decision on initialization</h4>
<p>Initialization is a more complex topic. This is because we must not only
consider whether class constructors execute, but we must also consider the
evaluation of the initializer:</p>
<pre class="neutralcode">int n = 5; // fine
int m = f(); // ? (depends on f)
Foo x; // ? (depends on Foo::Foo)
Bar y = g(); // ? (depends on g and on Bar::Bar)
</pre>
<p>All but the first statement expose us to indeterminate initialization
ordering.</p>
<p>The concept we are looking for is called <em>constant initialization</em> in
the formal language of the C++ standard. It means that the initializing
expression is a constant expression, and if the object is initialized by a
constructor call, then the constructor must be specified as
<code>constexpr</code>, too:</p>
<pre>struct Foo { constexpr Foo(int) {} };
int n = 5; // fine, 5 is a constant expression
Foo x(2); // fine, 2 is a constant expression and the chosen constructor is constexpr
Foo a[] = { Foo(1), Foo(2), Foo(3) }; // fine</pre>
<p>Constant initialization is always allowed. Constant initialization of
static storage duration variables should be marked with <code>constexpr</code>
or where possible the
<a href="https://github.com/abseil/abseil-cpp/blob/03c1513538584f4a04d666be5eb469e3979febba/absl/base/attributes.h#L540">
<code>ABSL_CONST_INIT</code></a>
attribute. Any non-local static storage
duration variable that is not so marked should be presumed to have
dynamic initialization, and reviewed very carefully.</p>
<p>By contrast, the following initializations are problematic:</p>
<pre class="badcode">// Some declarations used below.
time_t time(time_t*); // not constexpr!
int f(); // not constexpr!
struct Bar { Bar() {} };
// Problematic initializations.
time_t m = time(nullptr); // initializing expression not a constant expression
Foo y(f()); // ditto
Bar b; // chosen constructor Bar::Bar() not constexpr</pre>
<p>Dynamic initialization of nonlocal variables is discouraged, and in general
it is forbidden. However, we do permit it if no aspect of the program depends
on the sequencing of this initialization with respect to all other
initializations. Under those restrictions, the ordering of the initialization
does not make an observable difference. For example:</p>
<pre>int p = getpid(); // allowed, as long as no other static variable
// uses p in its own initialization</pre>
<p>Dynamic initialization of static local variables is allowed (and common).</p>
<h4>Common patterns</h4>
<ul>
<li>Global strings: if you require a global or static string constant,
consider using a simple character array, or a char pointer to the first
element of a string literal. String literals have static storage duration
already and are usually sufficient.</li>
<li>Maps, sets, and other dynamic containers: if you require a static, fixed
collection, such as a set to search against or a lookup table, you cannot
use the dynamic containers from the standard library as a static variable,
since they have non-trivial destructors. Instead, consider a simple array of
trivial types, e.g. an array of arrays of ints (for a "map from int to
int"), or an array of pairs (e.g. pairs of <code>int</code> and <code>const
char*</code>). For small collections, linear search is entirely sufficient
(and efficient, due to memory locality); consider using the facilities from
<a href="https://github.com/abseil/abseil-cpp/blob/master/absl/algorithm/container.h">absl/algorithm/container.h</a>
for the standard operations. If necessary, keep the collection in sorted
order and use a binary search algorithm. If you do really prefer a dynamic
container from the standard library, consider using a function-local static
pointer, as described below.</li>
<li>Smart pointers (<code>unique_ptr</code>, <code>shared_ptr</code>): smart
pointers execute cleanup during destruction and are therefore forbidden.
Consider whether your use case fits into one of the other patterns described
in this section. One simple solution is to use a plain pointer to a
dynamically allocated object and never delete it (see last item).</li>
<li>Static variables of custom types: if you require static, constant data of
a type that you need to define yourself, give the type a trivial destructor
and a <code>constexpr</code> constructor.</li>
<li>If all else fails, you can create an object dynamically and never delete
it by using a function-local static pointer or reference (e.g. <code>static
const auto& impl = *new T(args...);</code>).</li>
</ul>
<h3 id="thread_local">thread_local Variables</h3>
<p><code>thread_local</code> variables that aren't declared inside a function
must be initialized with a true compile-time constant,
and this must be enforced by using the
<a href="https://github.com/abseil/abseil-cpp/blob/master/absl/base/attributes.h">
<code>ABSL_CONST_INIT</code></a>
attribute. Prefer
<code>thread_local</code> over other ways of defining thread-local data.</p>
<p class="definition"></p>
<p>Starting with C++11, variables can be declared with the
<code>thread_local</code> specifier:</p>
<pre>thread_local Foo foo = ...;
</pre>
<p>Such a variable is actually a collection of objects, so that when different
threads access it, they are actually accessing different objects.
<code>thread_local</code> variables are much like
<a href="#Static_and_Global_Variables">static storage duration variables</a>
in many respects. For instance, they can be declared at namespace scope,
inside functions, or as static class members, but not as ordinary class
members.</p>
<p><code>thread_local</code> variable instances are initialized much like
static variables, except that they must be initialized separately for each
thread, rather than once at program startup. This means that
<code>thread_local</code> variables declared within a function are safe, but
other <code>thread_local</code> variables are subject to the same
initialization-order issues as static variables (and more besides).</p>
<p><code>thread_local</code> variable instances are destroyed when their thread
terminates, so they do not have the destruction-order issues of static
variables.</p>
<p class="pros"></p>
<ul>
<li>Thread-local data is inherently safe from races (because only one thread
can ordinarily access it), which makes <code>thread_local</code> useful for
concurrent programming.</li>
<li><code>thread_local</code> is the only standard-supported way of creating
thread-local data.</li>
</ul>
<p class="cons"></p>
<ul>
<li>Accessing a <code>thread_local</code> variable may trigger execution of
an unpredictable and uncontrollable amount of other code.</li>
<li><code>thread_local</code> variables are effectively global variables,
and have all the drawbacks of global variables other than lack of
thread-safety.</li>
<li>The memory consumed by a <code>thread_local</code> variable scales with
the number of running threads (in the worst case), which can be quite large
in a program.</li>
<li>An ordinary class member cannot be <code>thread_local</code>.</li>
<li><code>thread_local</code> may not be as efficient as certain compiler
intrinsics.</li>
</ul>
<p class="decision"></p>
<p><code>thread_local</code> variables inside a function have no safety
concerns, so they can be used without restriction. Note that you can use
a function-scope <code>thread_local</code> to simulate a class- or
namespace-scope <code>thread_local</code> by defining a function or
static method that exposes it:</p>
<pre>Foo& MyThreadLocalFoo() {
thread_local Foo result = ComplicatedInitialization();
return result;
}
</pre>
<p><code>thread_local</code> variables at class or namespace scope must be
initialized with a true compile-time constant (i.e. they must have no
dynamic initialization). To enforce this, <code>thread_local</code> variables
at class or namespace scope must be annotated with
<a href="https://github.com/abseil/abseil-cpp/blob/master/absl/base/attributes.h">
<code>ABSL_CONST_INIT</code></a>
(or <code>constexpr</code>, but that should be rare):</p>
<pre>ABSL_CONST_INIT thread_local Foo foo = ...;
</pre>
<p><code>thread_local</code> should be preferred over other mechanisms for
defining thread-local data.</p>
<h2 id="Classes">Классы</h2>
<p>Классы являются основным строительным блоком в C++. И, конечно же, используются
они очень часто. В этой секции описаны основные правила и запреты, которым нужно
следовать при использовании классов.</p>
<h3 id="Doing_Work_in_Constructors">Код в конструкторе</h3>