Reputation: 8538
If a non-literal class type has no constexpr
constructor (it is not constexpr
constructible), does a non-static constexpr
member function make any sense? I mean if you cannot construct the object at compile time, how would you able to use its member functions?
Anyway, the major compilers don't complain about it, which makes me think it is allowed by the standard.
Nevertheless, you are able to use such constexpr
member functions in runtime without any problem. The only question now what is the effect of constexpr
in this case, if any. My best guess is that the return value of the constexpr
member is being evaluated at compile-time (if possible), so on a run-time call it have to do a simple copy.
Is my guess correct, or is the constexpr
specifier absolutely meaningless in this case (i.e. the member function is being evaluated at runtime)?
Upvotes: 3
Views: 845
Reputation: 283971
The premise of your question seems to be that only constexpr
functions can be evaluated at compile-time.
This premise is incorrect. The compiler can precompute anything it can figure out a way to do, as long as the exact side result and side-effects are produced (as-if rule).
What constexpr
provides is a guarantee that certain expressions will be evaluated at compile-time by every compiler (it's not a "quality of implementation" issue), which makes it possible to use them in contexts where a compile-time value is needed, such as non-type template arguments, operands of case
clauses in switch
statements, etc.
The specific details around constexpr
functions include that there has to be at least one set of arguments (the target instance is an implied argument) such that the constexpr
evaluation rules are met. If that isn't true, your program is ill-formed and its runtime behavior is not specified at all, so don't go adding constexpr
where it doesn't logically belong.
However, compilers aren't required to diagnose violations of this rule. That means that "major compilers don't complain about it" should not be in any way interpreted as assurance that the code is correct.
Standard's wording, section 7.1.5 (draft n4582)
For a
constexpr
function orconstexpr
constructor that is neither defaulted nor a template, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression, or, for a constructor, a constant initializer for some object, the program is ill-formed; no diagnostic required.
Upvotes: 1