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

Clang behaves somewhat weirdly with pointer to member field cast inside a class not completed and inheritance

Open Rush10233 opened this issue 2 years ago • 2 comments

The following code compiles normally in clang:

struct A { int i; };
struct B:A { int j; };
struct C:B { int k; static_assert((int(B::*))&C::k, ""); };

But it's rejected by gcc which complains that &C::k should not be constant before the class C is completed:

<source>:3:35: error: non-constant condition for static assertion
    3 | struct C:B { int k; static_assert((int(B::*))&C::k, ""); };
      |                                   ^~~~~~~~~~~~~~~~
<source>:3:35: error: '&C::k' is not a constant expression when the class 'C' is still incomplete
Compiler returned: 1

Note that the static_assert expression requires its first parameter to be compile-time constant. It seems at least one of the compilers does the wrong thing. Since the standard of class member variable pointer assignment looks a little complex, we currently cannot judge for certain which behavior is reasonable. We hope that can be further identified.

https://godbolt.org/z/MWeYx7sYq

Rush10233 avatar Feb 14 '24 13:02 Rush10233

@llvm/issue-subscribers-clang-frontend

Author: None (Rush10233)

The following code compiles normally in clang:
struct A { int i; };
struct B:A { int j; };
struct C:B { int k; static_assert((int(B::*))&amp;C::k, ""); };

But it's rejected by gcc which complains that &amp;C::k should not be constant before the class C is completed:

&lt;source&gt;:3:35: error: non-constant condition for static assertion
    3 | struct C:B { int k; static_assert((int(B::*))&amp;C::k, ""); };
      |                                   ^~~~~~~~~~~~~~~~
&lt;source&gt;:3:35: error: '&amp;C::k' is not a constant expression when the class 'C' is still incomplete
Compiler returned: 1

Note that the static_assert expression requires its first parameter to be compile-time constant. It seems at least one of the compilers does the wrong thing. Since the standard of class member variable pointer assignment looks a little complex, we currently cannot judge for certain which behavior is reasonable. We hope that can be further identified.

https://godbolt.org/z/MWeYx7sYq

llvmbot avatar Feb 14 '24 15:02 llvmbot

If we change it to C::* then all implementations accept: https://godbolt.org/z/Tz97rosKj

Note if we change the order of the static_assert and field: https://godbolt.org/z/G94cT7E4s

struct A { int i; };
struct B:A { int j; };
struct C:B { 
  static_assert((int(B::*))&C::k, "");
  int k=0; 
};

Implementation agree, but this is IFNDR b/c of: basic.lookup.general p6

I think gcc is wrong on this one.

CC @zygoloid

shafik avatar Feb 14 '24 18:02 shafik