Issue 69319
Summary clang-tidy: complains about const_cast adding const [cppcoreguidelines-pro-type-const-cast]
Labels clang-tidy
Assignees
Reporter BikingGlobetrotter
    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
_______________________________________________
llvm-bugs mailing list
llvm-bugs@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to