[try Beta version]
Not logged in

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

Sep 27, 2024 at 6:54pm
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 Sep 27, 2024 at 7:02pm
Sep 28, 2024 at 8:40am
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 Sep 28, 2024 at 8:53am
Sep 28, 2024 at 6:28pm
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
}

Sep 28, 2024 at 8:20pm
Hmm, are you able to implement the copy constructor correctly and still have it work? I can't...
Last edited on Sep 28, 2024 at 8:22pm
Sep 28, 2024 at 9:48pm
Good point. I suppose you could remove x. I'm not sure what the point of all this is, though.
Topic archived. No new replies allowed.