constexpt指针如何存在并且constevel函数在编译时返回指针?

问题描述 投票:0回答:1

我正在浏览 constexpr 和 consteval 的主题,发现了以下内容,

  1. 我们可以拥有 CONSTEXPR 类型的指针
  2. CONSTEVAL 函数可以返回 CONSTEXPR 变量的指针

我的问题是,上面的 2 个怎么可能?

以上两个问题是因为,据我所知,所有变量都是在运行时在内存中创建的,而指针是该内存的地址。

那么,CONSTEXPR 类型的指针如何存在(因为 CONSTEXPR 变量必须在编译时初始化)? CONSTEVAL 函数如何在编译期间返回 CONSTEXPR 变量的指针?


 constexpr int a{1};

 consteval const int* aptrfunc()  //How can this function return a pointer at compile time
 {
     return &a;
 }

 int main()
 {
      constexpr const int* aptr{&a};   //How can this exist at compiletime?
      std::cout<<aptr<<'\n';           //Prints address of a
      std::cout<<aptrfunc()<<'\n';     //Prints address of a
      return 0;
  }
c++ pointers constexpr consteval
1个回答
0
投票

constexpr 变量确实需要在编译时初始化。它们必须具有在编译时确定的常量值。 然而,constexpr变量的地址仍然可以在编译时获取,因为它不一定涉及变量的实际值,只是它在内存中的地址,这是在编译时已知的。

consteval 函数在编译时求值,并且它们可以返回也在编译时确定的值。 在您的示例中, consteval 函数 aptrfunc 返回指向 constexpr 变量 a 的指针。这是可能的,因为 a 的地址在编译时是已知的,即使 a 的值在编译时也是已知的。

让我们分析您的代码:

constexpr int a{1};

consteval const int* aptrfunc()
{
    return &a;  // The address of 'a' is known at compile-time.
}

int main()
{
    constexpr const int* aptr{&a};  // This is a pointer to 'a', and its address is known at compile-time.
    std::cout << aptr << '\n';      // This will print the address of 'a' at compile-time.
    std::cout << aptrfunc() << '\n'; // This also returns the address of 'a' at compile-time.
    return 0;
}

在这两种情况下,指针都指向 a 的地址,该地址在编译时已知,因为它是 constexpr 变量。 a 的实际值在编译时也是已知的。

© www.soinside.com 2019 - 2024. All rights reserved.