llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

Clang accepts invalid program involving static_cast from class type to const bool& with conversion operator

Open ranaanoop opened this issue 2 years ago • 4 comments

The following invalid program is accepted by clang. Demo


struct C {
    explicit operator bool() const {
        return true;
    }
};
 
int main() {

    C c;

    auto b = static_cast<const bool &>(c);//accepted by clang only

}

ranaanoop avatar Jul 17 '24 14:07 ranaanoop

@llvm/issue-subscribers-clang-frontend

Author: Anoop Rana (ranaanoop)

The following invalid program is accepted by clang. [Demo](https://godbolt.org/z/oM33ffsEG)

struct C {
    explicit operator bool() const {
        return true;
    }
};
 
int main() {

    C c;

    auto b = static_cast&lt;const bool &amp;&gt;(c);//accepted by clang only

}

llvmbot avatar Jul 17 '24 14:07 llvmbot

I believe this is direct-initialization and so explicit conversion are allowd: https://eel.is/c++draft/over.match.ref#1.1

So I believe clang is correct and maybe this gcc bug report is related: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=83615

shafik avatar Jul 18 '24 19:07 shafik

Do I understand it correctly that [over.match.ref]/1.1 requires the conversion function to return an lvalue reference in this case (of initializing an lvalue reference)?

MagentaTreehouse avatar Jul 18 '24 20:07 MagentaTreehouse

Do I understand it correctly that [over.match.ref]/1.1 requires the conversion function to return an lvalue reference in this case (of initializing an lvalue reference)?

https://cplusplus.github.io/CWG/issues/2919.html

t3nsor avatar Aug 08 '24 00:08 t3nsor