Constexpr functions not called at compile-time if result is ignored

后端 未结 1 1670
孤独总比滥情好
孤独总比滥情好 2021-01-28 05:29

I was investigating some rather weird code-coverage results of constexpr functions (compile-time calls can\'t get instrumented by the code-coverage tool I use), and

相关标签:
1条回答
  • 2021-01-28 05:40

    It might be confusing, but constexpr functions should be called at compile time only in constexpr contexts (assignation to constexpr variable, use for array size or template parameter, ...).

    In regular context, functions are called at runtime. Optimizer might resolve that function at compile time (as for any other functions following the as-if rule). constexpr is indeed a good hint for optimization to happen.

    You could argue that since constexpr functions cannot have side-effects

    They can have side effect, see following valid example:

    constexpr int f(int i)
    {
        if (i == 0) return 0;
        std::cout << i << std::endl;
        return i;
    }
    
    int main()
    {
        [[maybe_unused]] constexpr int zero = f(0); // Compile time
        f(42); // runtime
    }
    

    Demo

    0 讨论(0)
提交回复
热议问题