llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
28.04k stars 11.58k forks source link

[clang-tidy] `readability-redundant-casting` false positive on inheritance #108846

Open felix642 opened 3 days ago

felix642 commented 3 days ago

The following code snippet will trigger readability-redundant-casting and suggests removing the static_cast. Doing so would lead to a compilation failure.

class A
{
    int a;
};

class B : public A
{

};

int main()
{
    A a;
    B b = static_cast<B>(a);  // [warning: redundant explicit casting to the same type 'B' as the sub-expression, remove this casting [readability-redundant-casting]]
}

Godbolt : https://godbolt.org/z/qY1v196qG

dl8sd11 commented 20 hours ago

Hi, I am new to clang-tidy and I would like to try on this issue :)

I think the RedundantCastingCheck checks the casting for pointers but for this example the casting is done on value type.

I try to add the example to the unit test but it gets a compiler error:

/usr/local/google/home/gcchen/Workspace/llvm-project/ninja-build/tools/clang/tools/extra/test/clang-tidy/checkers/readability/Output/redundant-casting.cpp.tmp.cpp:61:9: error: no matching conversion for static_cast from 'A' to 'B' [clang-diagnostic-error]
   61 |   B b = static_cast<B>(value);

I found the code cannot compile on the c++17 standard but it can compile on c++20.

cmake -S llvm -B ninja-build -G Ninja -DCMAKE_BUILD_TYPE=Debug
cd ninja-build
cmake -DLLVM_ENABLE_PROJECTS="clang;clang-tools-extra" -GNinja .
ninja check-clang-tools

Do you know how to compile it with the c++20 standard?

BTW, I am also thinking when this kind of casting could be useful. (why is it allowed by c++20)

felix642 commented 20 hours ago

Hi @dl8sd11, please have a look at the file llvm-project/clang-tools-extra/test/clang-tidy/make-unique-inaccessible-ctors.cpp for an example that uses both C++14/17 and C++20.