Skip to content

Commit 5bddadf

Browse files
[CodingStandard] Rework anonymous namespace section to cover visibility more broadly (#126775)
- Rename anonymous namespace section and rework it to cover visibility more broadly. - Add language suggesting restricting visibility as much as possible, using various C++ facilities. --------- Co-authored-by: Aaron Ballman <[email protected]>
1 parent cebb8f7 commit 5bddadf

File tree

1 file changed

+17
-11
lines changed

1 file changed

+17
-11
lines changed

llvm/docs/CodingStandards.rst

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1579,17 +1579,23 @@ clarification.
15791579

15801580
.. _static:
15811581

1582-
Anonymous Namespaces
1583-
^^^^^^^^^^^^^^^^^^^^
1584-
1585-
After talking about namespaces in general, you may be wondering about anonymous
1586-
namespaces in particular. Anonymous namespaces are a great language feature
1587-
that tells the C++ compiler that the contents of the namespace are only visible
1588-
within the current translation unit, allowing more aggressive optimization and
1589-
eliminating the possibility of symbol name collisions. Anonymous namespaces are
1590-
to C++ as "static" is to C functions and global variables. While "``static``"
1591-
is available in C++, anonymous namespaces are more general: they can make entire
1592-
classes private to a file.
1582+
Restrict Visibility
1583+
^^^^^^^^^^^^^^^^^^^
1584+
1585+
Functions and variables should have the most restricted visibility possible.
1586+
For class members, that means using appropriate `private`, `protected`, or `public`
1587+
keyword to restrict their access. For non-member functions, variables, and classes,
1588+
that means restricting visibility to a single `.cpp` file if it's not referenced
1589+
outside that file.
1590+
1591+
Visibility of file-scope non-member variables and functions can be restricted to
1592+
the current translation unit by using either the `static` keyword or an anonymous namespace.
1593+
Anonymous namespaces are a great language feature that tells the C++ compiler that
1594+
the contents of the namespace are only visible within the current translation unit,
1595+
allowing more aggressive optimization and eliminating the possibility of symbol
1596+
name collisions. Anonymous namespaces are to C++ as `static` is to C functions and
1597+
global variables. While `static` is available in C++, anonymous namespaces are more
1598+
general: they can make entire classes private to a file.
15931599

15941600
The problem with anonymous namespaces is that they naturally want to encourage
15951601
indentation of their body, and they reduce locality of reference: if you see a

0 commit comments

Comments
 (0)