class test{
public:
constexpr test(){}
constexprintoperator+(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.
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
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
}