函数内constexpr变量的行为

Cev*_*vik 2 c++ constexpr c++11

我想知道在函数内部定义constexpr变量时内部会发生什么.程序是否存储了被调用函数的constexpr变量的每个版本?

例:

template <class T, std::size_t M, std::size_t N>
template <std::size_t M2, std::size_t N2>
Matrix<T, M, N>::Matrix(const Matrix<T, M2, N2>& m)
{
    constexpr T m_min(MATHS::min(M, M2));
    constexpr T n_min(MATHS::min(N, N2));
    std::size_t i(0), j(0);
    for ( ; i < m_min ; ++i )
    {
        for ( j = 0 ; j < n_min ; ++j )
            m_elts[i][j] = m.m_elts[i][j];
        for ( ; j < N ; ++j )
            m_elts[i][j] = MATHS::CST<T>::ZERO;
    }
    for ( ; i < M ; ++i )
    {
        for ( j = 0 ; j < N ; ++j )
            m_elts[i][j] = MATHS::CST<T>::ZERO;
    }
}

//m_elts is : std::array<std::array<T, N>, M> m_elts;
Run Code Online (Sandbox Code Playgroud)

Sha*_*our 5

这将取决于优化器和示例,但总的来说,我会说如果变量不是ODR使用的(松散地采用变量地址或绑定到引用)那么很可能是编译器在运行时不需要在某处存储值.

鉴于以下设计的示例与您提供的示例松散相似:

#include <cstdio>
#include <algorithm>

template <typename T, size_t M, size_t N>
void func1( int x1, int x2, int x3 )
{
  constexpr T y1 = std::min(M,N) ;
  int y2 = x2 ;
  int z1 = x1 + y1 ;
  int z2 = x3 + y2 ;

  printf( "%d %d %d\n", x1, z1, z2 ) ;
}

template <typename T, size_t M, size_t N>
void func2( int x1, int x2, int x3 )
{
  constexpr int y1 = std::min(M,N) ;
  int y2 = x2 ;
  int z1 = x1 + y1 ;
  int z2 = x3 + y2 ;

  const int *p1 = &y1 ;

  printf( "%d %d %d %p\n", x1, z1, z2, p1 ) ;
}

int main()
{
  int x = 1, y = 2, z = 3 ;
  func1<int,10,20>( x, y, z ) ;
  func2<int,10,20>( x, y, z ) ;
}
Run Code Online (Sandbox Code Playgroud)

我们可以看到使用一个godbolt实例,我们可以在func1constexpr变量中看到它y1被替换为文字:

leal     10(%rdi), %edx #, z1
Run Code Online (Sandbox Code Playgroud)

它不是odr-used,因为我们不接受它的地址,也没有绑定它的引用,但是func2我们确实使用它的地址并使用它,所以它需要在运行时存在:

movl    $10, 12(%rsp)   #, y1
Run Code Online (Sandbox Code Playgroud)