c++ - constexpr 函数可以返回局部对象的指针吗?

标签 c++ c++14

constexpr 函数定义为 (c++14)

A constexpr function must satisfy the following requirements:

  • it must not be virtual
  • its return type must be LiteralType each of its parameters must be LiteralType
  • there exists at least one set of argument values such that an invocation of the function could be an evaluated subexpression of a core constant expression (for constructors, use in a constant initializer is sufficient) (since C++14). No diagnostic is required for a violation of this bullet.

the function body must be either deleted or defaulted or contain any statements except:

  • an asm declaration
  • a goto statement
  • a statement with a label other than case and default
  • a try-block
  • a definition of a variable of non-literal type
  • a definition of a variable of static or thread storage duration
  • a definition of a variable for which no initialization is performed.

现在下面的func1满足要求编译

constexpr int * func1 (int a)
{
  int b = 4;
  return &b;
}
int main()
{
    constexpr int * a = func1(3);
    int arr[*a];  
    std::cout << a << std::endl;
}

现在我的问题是 func1 为什么是 constexpr。它如何在编译时知道局部变量的地址?

我使用的是 gcc 6.4.0

最佳答案

How does it know address of local variable at compile time?

不是。

你引述中的第三个要点是永不满足:

There exists at least one set of argument values such that an invocation of the function could be an evaluated subexpression of a core constant expression (for constructors, use in a constant initializer is sufficient) (since C++14). No diagnostic is required for a violation of this bullet.

编译器只是不提示它,因为它不是必需的,直到你通过尝试在需要正确的 constexpr 函数的东西中使用 func1 来让它提示,例如:

std::array<int, func(3)> d;

这不会编译,您的编译器会告诉您原因。

关于c++ - constexpr 函数可以返回局部对象的指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50467254/

相关文章:

c++ - 实现抽象类的类中的多态函数

c++ - 从临时对象创建一对

c++ - 这里发生了什么?我将结果分配给 C++ 中的结果

c++ - 在 c++14 lambda 表达式中捕获和移动 unique_ptr

c++ - native WMI 提供程序中的 UINT64 不会在某些系统上返回数据

c++ - operator= 结合 new 运算符的使用

c++ - 更快的二进制加法 C++

c++ - 什么时候可以应用自动返回类型?

c++ - 如何读取未知数量的输入?

c++ - 默认析构函数有什么用?