how to initialize a constexpr reference

前端 未结 3 1649
余生分开走
余生分开走 2020-11-28 13:29

I am trying to initialize a constexpr reference with no success. I tried

#include 

constexpr int& f(int& x) // can defi         


        
3条回答
  •  忘掉有多难
    2020-11-28 14:11

    1. Are constexpr references ever useful? (i.e., "better" than const references)

    They are guaranteed to be initiailized before the program starts, whereas a reference to const can be initialized during dynamic initialization, after the program starts running.

    1. If yes, how can I effectively define them?

    A constexpr reference has to bind to a global, not a local variable (or more formally, it has to bind to something with static storage duration).

    A reference is conceptually equivalent to taking the address of the variable, and the address of a local variable is not a constant (even in main which can only be called once and so its local variables are only initialized once).

提交回复
热议问题