https://gcc.gnu.org/bugzilla/show_bug.cgi?id=126357

            Bug ID: 126357
           Summary: Calling member function before base subobject
                    initialization in constant evaluation not rejected
           Product: gcc
           Version: 16.1.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: gongke at ios dot ac.cn
  Target Milestone: ---

Consider this program:

```cpp
#include <cstddef>
struct A {
    constexpr A(int x) : val(x) {}
    int val;
};
struct B : A {
    constexpr int f() const { return 42; }
    constexpr B() : A(f()) {} // undefined behavior: calls member function f()
but base A not yet initialized
};
constexpr int foo() {
    constexpr B b{};
    return b.val;
}
int main() {
    constexpr auto x = foo();
    return 0;
}
```

C++20 final draft N4861 [class.base.init]/16:
> Member functions (including virtual member functions, 11.7.2) can be called 
> for an object under construction. Similarly, an object under construction can 
> be the operand of the typeid operator (7.6.1.7) or of a dynamic_cast 
> (7.6.1.6). However, if these operations are performed in a ctor-initializer 
> (or in a function called directly or indirectly from a ctor-initializer ) 
> before all the mem-initializer s for base classes have completed, the program 
> has undefined behavior. [Example:
> ```cpp
> class A {
> public:
>   A(int);
> };
> class B : public A {
>   int j;
> public:
>   int f();
>   B() : A(f()), // undefined behavior: calls member function but base A not 
> yet initialized
>   j(f()) { }    // well-defined: bases are all initialized
> };
> ```

So this is UB and should be rejected in constant evaluation. Neither GCC nor
Clang rejects it. [godbolt](https://godbolt.org/z/er876Wbj6)

Reply via email to