| 1 |
.. title:: clang-tidy - portability-std-allocator-const |
| 2 |
|
| 3 |
portability-std-allocator-const |
| 4 |
=============================== |
| 5 |
|
| 6 |
Report use of ``std::vector<const T>`` (and similar containers of const |
| 7 |
elements). These are not allowed in standard C++, and should usually be |
| 8 |
``std::vector<T>`` instead." |
| 9 |
|
| 10 |
Per C++ ``[allocator.requirements.general]``: "T is any cv-unqualified object |
| 11 |
type", ``std::allocator<const T>`` is undefined. Many standard containers use |
| 12 |
``std::allocator`` by default and therefore their ``const T`` instantiations are |
| 13 |
undefined. |
| 14 |
|
| 15 |
libc++ defines ``std::allocator<const T>`` as an extension which will be removed |
| 16 |
in the future. |
| 17 |
|
| 18 |
libstdc++ 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 |
|
| 30 |
Code bases only compiled with libc++ may accrue such undefined usage. This |
| 31 |
check finds such code and prevents backsliding while clean-up is ongoing. |