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/