c++ - 关于constexpr函数的一个问题

浏览:31日期:2023-05-14

问题描述

先看代码

#include <iostream>#include <cstdlib>#include <cstdio>//#include 'test.h'using namespace std;constexpr int screen(int x){ return x; }int main(){ int x = 0; int z = screen(x); cout << z<<endl; return 0;}

  在C++ Primer一书中说到constexpr函数定义的约定:函数的返回类型以及所有的形参类型必须是字面值类型(即编译过程就能得到结果的类型)。但是同时又说constexpr函数不一定返回常量表达式。感觉前后有一些矛盾,就像上面的代码一样,通过 g++ test.cpp -std=c00x 的编译运行都是没有问题的,这里应该怎么理解?

问题解答

回答1:

看看这个:A constexpr function is not required to return a constant expression?

回答2:

C++标准文档n45675.20小节讲的就是这个

int main(){ int x = 0; int z = screen(x); //因为z是非constexpr的,不要求screen是constexpr的 cout << z<<endl; return 0;}

int main(){ int x = 0; constexpr int z = screen(x); //错误!! x的lifetime开始于screen(x)的外部 cout << z<<endl; return 0;}

int main(){ constexpr int z = screen(0); //screen(0)是常量表达式, 对于screen内部,x的lifetime开始于函数内部 cout << z<<endl; return 0;}回答3:

  可以这样认为:C++不要求constexpr函数必须返回常量表达式(以问题中的screen constexpr函数为例)

如果在不需要常量表达式的上下文,如: int z = screen(x); 可以不返回常量表达式,此时编译器不会检查函数的结果是否会返回常量表达式。

如果是在需要常量表达式的上下文中,如: constexpr int z = screen(x); 那么,constexpr函数必须可以返回常量表达式。此时编译器会去检查函数返回的结果是不是常量表达式,如果不是,就会报错。

相关文章: