CistExPR是C++ 11中的一个特性。其主要思想是通过在编译时而不是运行时进行计算来提高程序的性能。请注意,一旦一个程序被开发人员编译并最终确定,它就会被用户运行多次。这样做的目的是花时间进行编译,并在运行时节省时间(类似于 模板元编程 )
constexpr指定可以在编译时计算对象或函数的值,并且可以在其他常量表达式中使用该表达式。例如,在下面的代码中,product()是在编译时计算的。
// constexpr function for product of two numbers. // By specifying constexpr, we suggest compiler to // to evaluate value at compile time constexpr int product( int x, int y) { return (x * y); } int main() { const int x = product(10, 20); cout << x; return 0; } |
输出:
200
函数可以声明为constexpr
- 在C++ 11中,一个CONTHEXPR函数应该只包含一个返回语句。C++ 14允许多个语句。
- constexpr函数应该只引用常量全局变量。
- constexpr函数只能调用其他constexpr函数,不能调用简单函数。
- 函数不应为void类型,在constepr函数中不允许使用前缀增量(++v)之类的运算符。
constexpr与内联函数: 两者都是为了提高性能,内联函数要求编译器在编译时进行扩展,并节省函数调用开销。在内联函数中,表达式总是在运行时求值。constexpr不同,这里的表达式是在编译时计算的。
constexpr的性能改进示例: 考虑下面的C++程序
// A C++ program to demonstrate the use of constexpr #include<iostream> using namespace std; constexpr long int fib( int n) { return (n <= 1)? n : fib(n-1) + fib(n-2); } int main () { // value of res is computed at compile time. const long int res = fib(30); cout << res; return 0; } |
当上述程序在GCC上运行时,需要 0.003秒 (我们可以使用 时间命令 )
如果我们从下面的行中删除const,那么fib(5)的值不会在编译时计算,因为constepr的结果不会在const表达式中使用。
Change, const long int res = fib(30); To, long int res = fib(30);
在进行上述更改后,程序所用的时间会变长 0.017秒 .
constexpr与构造函数: constexpr也可以用于构造函数和对象。看见 这 对于可以使用constexpr的构造函数的所有限制。
// C++ program to demonstrate uses of constexpr in constructor #include <bits/stdc++.h> using namespace std; // A class with constexpr constructor and function class Rectangle { int _h, _w; public : // A constexpr constructor constexpr Rectangle ( int h, int w) : _h(h), _w(w) {} constexpr int getArea () { return _h * _w; } }; // driver program to test function int main() { // Below object is initialized at compile time constexpr Rectangle obj(10, 20); cout << obj.getArea(); return 0; } |
输出:
200
constexpr vs const 它们有不同的用途。constexpr主要用于优化,而const则用于实际的const对象,比如Pi的值。 这两种方法都可以应用于成员方法。成员方法被设置为常量,以确保该方法不会发生意外更改。另一方面,使用constexpr的想法是在编译时计算表达式,以便在运行代码时节省时间。 const只能与非静态成员函数一起使用,而constexpr可以与成员和非成员函数一起使用,即使与构造函数一起使用,但条件是参数和返回类型必须是文本类型。
本文由Utkarsh Trivedi撰稿。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论