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