<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/69319>69319</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
clang-tidy: complains about const_cast adding const [cppcoreguidelines-pro-type-const-cast]
</td>
</tr>
<tr>
<th>Labels</th>
<td>
clang-tidy
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
BikingGlobetrotter
</td>
</tr>
</table>
<pre>
For the following code, clang-tidy raises a "cppcoreguidelines-pro-type-const-cast" issue.
`
#include <algorithm>
#include <array>
#include <charconv>
#include <cstdio>
#include <string>
#include <type_traits>
template <std::size_t N>
void AppendToCharsResult(
std::wstring& str, const char (&buffer)[N], std::to_chars_result result)
{
// simple conversion from char to wchar_t (as no critical characters are expected)
wchar_t wbuffer[N];
auto wbufferend =
std::copy(static_cast<const char*>(buffer), const_cast<const char*>(result.ptr), wbuffer);
str.insert(str.end(), wbuffer, wbufferend);
}
template <typename T>
std::enable_if_t<std::is_integral_v<T>> AppendValue(std::wstring& str, const T& value)
{
char buffer[512];
AppendToCharsResult(str, buffer, std::to_chars(buffer, buffer + sizeof(buffer), value));
}
int main()
{
std::wstring s;
AppendValue(s, 5);
return 0;
}
`
It recommends to not use the const_cast, as "Modifying a variable that was declared const is undefined behavior, even with const_cast.". Actually, we are "adding" constness, so this cannot result in undefined behavior.
The calling code, cannot remove the const_cast completely, since this results in a compiler that not know how to call std::copy with having a `const char*` and `mutable char*`. Replacing const_cast with static_cast would be possible, but that is less specific.
For me, it looks like the cppcoreguidelines-pro-type-const-cast test is too aggressive not differentiating between casts that add constness and casts that remove constness.
See godbolt for reference.
https://godbolt.org/z/nd6hfKhb4
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyMVk1v4zgS_TX0pRBDpvwRHXxwnPZisdg-9ARzNSiyJHFCkQJZssf96wekZFvOJDN9UYzUx3v1qlikCEHXFnHLVi9s9ToT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