Why const literal class is not a constexpr even if initialized from a constexpr?

1
2
3
4
5
6
7
8
9
10
11
12
class test{
    public:
    constexpr test(){}

    constexpr int operator+(const test& rhs) const {
        return 1+rhs.x  ;
    }

    int x = 10 ;
};
const test t0=test();
constexpr test t=t0;


The error I received are:
error: the value of ‘t0’ is not usable in a constant expression
note: ‘t0’ was not declared ‘constexpr’

Here t0 is not constexpr even if it is declared to be a const object and initialized from a constexpr (note that test() is a constant expression; if I use test() to initialize t, there is no error). I don't understand why is that because everything in t0 is unchangeable and can be known at compile time. Visual Studio suggests that the initialization of t attemps to access run-time storage, but I cannot figure out what run-time storage of t0 is needed. Looking forward to some help to explain why t0 is not considered constexpr, while test() is.

PS, below is excerpted from the first paragraph of section 2.4.4 of text "C++ Primer" which suggests that t0 should be constexpr:
A const object that is initialized from a constant expression is also a constant expression.

Last edited on
It works for integers but not for class types.

https://en.cppreference.com/w/cpp/language/constant_expression#Usable_in_constant_expressions
a variable is usable in constant expressions at a point P if the variable is a constexpr variable, or it is a constant-initialized variable of reference type or of const-qualified integral or enumeration type and the definition of the variable is reachable from P
Last edited on
If you add a constexpr copy constructor it seems to work for me.
1
2
3
4
5
6
7
8
9
10
11
class test{
public:
    constexpr test(){}
    constexpr test(const test&){}
    int x = 10;
};

int main() {
    const test t0;
    constexpr test t = t0;  // uses copy ctor
}

Hmm, are you able to implement the copy constructor correctly and still have it work? I can't...
Last edited on
Good point. I suppose you could remove x. I'm not sure what the point of all this is, though.
Registered users can post here. Sign in or register to post.