xref: /llvm-project/clang-tools-extra/docs/clang-tidy/checks/portability/std-allocator-const.rst (revision 6e566bc5523f743bc34a7e26f050f1f2b4d699a8)
1.. title:: clang-tidy - portability-std-allocator-const
2
3portability-std-allocator-const
4===============================
5
6Report use of ``std::vector<const T>`` (and similar containers of const
7elements). These are not allowed in standard C++, and should usually be
8``std::vector<T>`` instead."
9
10Per C++ ``[allocator.requirements.general]``: "T is any cv-unqualified object
11type", ``std::allocator<const T>`` is undefined. Many standard containers use
12``std::allocator`` by default and therefore their ``const T`` instantiations are
13undefined.
14
15libc++ defines ``std::allocator<const T>`` as an extension which will be removed
16in the future.
17
18libstdc++ and MSVC do not support ``std::allocator<const T>``:
19
20.. code:: c++
21
22  // libstdc++ has a better diagnostic since https://gcc.gnu.org/bugzilla/show_bug.cgi?id=48101
23  std::deque<const int> deque; // error: static assertion failed: std::deque must have a non-const, non-volatile value_type
24  std::set<const int> set; // error: static assertion failed: std::set must have a non-const, non-volatile value_type
25  std::vector<int* const> vector; // error: static assertion failed: std::vector must have a non-const, non-volatile value_type
26
27  // MSVC
28  // error C2338: static_assert failed: 'The C++ Standard forbids containers of const elements because allocator<const T> is ill-formed.'
29
30Code bases only compiled with libc++ may accrue such undefined usage. This
31check finds such code and prevents backsliding while clean-up is ongoing.
32