llvm / llvm/llvm-project

Calling member function before base subobject initialization in constant evaluation not rejected

Open
#211,286 6 comments 0 reactions 0 assignees View on GitHub
clang:frontend confirmed constexpr
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

Consider this program:

```cpp
#include
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/Tca13GY97)

Contributor guide

Open the contributing guide

Research direction

Start with the provided C++ reproducer and investigate constant-evaluation handling for constructor mem-initializers and calls made before base-class initialization. Compare current compiler behavior with the C++20 rule quoted in the issue; done means the invalid constexpr initialization is rejected with an appropriate diagnostic.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Clearly specified
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.