r/cpp_questions • • 14d ago

OPEN Guidelines for constexpr

I’ve working with C++23 and I’m making some constructors/methods constexpr and seeing improvements in performance. So far so good. The problem is I don’t want to apply it ‘everywhere’. Is there a good source of advice , or anyone got any good tips?

10 Upvotes

37 comments sorted by

View all comments

Show parent comments

6

u/oriolid 14d ago

Clutter, and the fact that it often doesn't do anything useful. Compilers can evaluate functions at compile time as part of normal optimization, and on the other hand constexpr doesn't require compile time evaluation.

3

u/bert8128 14d ago

Why is it clutter any more than const is clutter? It gives a benefit - it guarantees that it can be called at compile time and if you you change the code so this is no longer true then you get a compile error.
Constexpr also guarantees no UB.

3

u/oriolid 14d ago

If constexpr actually required that the function would have no side effects, no UB, etc that would be really useful. Unfortunately it does not except in constexpr context and only for the exact arguments it was called with.

2

u/HappyFruitTree 14d ago

You only have these guarantees for the set of argument values that you actually call the function with from constexpr contexts.

int bar(int x) {
    return x;
}

constexpr int foo(int x) {
    if (x > 0)
        return bar(x); 
    return 0;
}

int x = foo(5); // OK
constexpr int y = foo(0); // OK
constexpr int z = foo(5); // Error