Why can't reinterpret_cast be used in a constant expression?

Viewed 717

I've run into the following error:

class NormalClass
{
public:
    constexpr NormalClass() : arr{}, debug_ptr((int*)arr)
    {
//'reinterpret_cast' is not a constant expression
//cast that performs the conversions of a reinterpret_cast is not allowed in a constant expression
    }

public:

    char arr[5];
    int* debug_ptr;


};

constinit NormalClass normal;

int main()
{

}

Originally this was in a template, with (T*) cast. Why is it that a cast like this isn't allowed in a constexpr?

2 Answers

Why can't reinterpret_cast be used in a constant expression?

Because the C++ language spec says so. See [expr.const]/5.15:

An expression E is a core constant expression unless the evaluation of E, ... would evaluate one of the following:

5.15   a reinterpret_­cast ([expr.reinterpret.cast]);


Also note that reinterpreting char[] as int and then accessing it is undefined behavior - a strict aliasing violation. As soon as the pointer debug_ptr is dereferenced in the actual program, there will be UB.

Related