- 论坛徽章:
- 0
|
本帖最后由 AD8018 于 2012-02-06 15:37 编辑
这个是优化时计算,不叫编译时计算吧
不优化的情况下,反汇编出来看,计算过程全在代码里。
--------------------------------------------------
更正最新的学习结果,
http://en.wikipedia.org/wiki/C%2B%2B11
看了下constexpr, 的确是能保证编译时计算的
C++11 introduced the keyword constexpr, which allows the user to guarantee that a function or object constructor is a compile-time constant. The above example can be rewritten as follows:
constexpr int get_five() {return 5;}
int some_value[get_five() + 7]; // Create an array of 12 integers. Legal C++11
This allows the compiler to understand, and verify, that get_five is a compile-time constant.
The use of constexpr on a function imposes some limitations on what that function can do. First, the function must have a non-void return type. Second, the function body cannot declare variables or define new types. Third, the body may only contain declarations, null statements and a single return statement. There must exist argument values such that, after argument substitution, the expression in the return statement produces a constant expression.
Prior to C++11, the values of variables could only be used in constant expressions if the variables are declared const, have an initializer which is a constant expression, and are of integral or enumeration type. C++11 removes the restriction that the variables must be of integral or enumeration type if they are defined with the constexpr keyword:
constexpr double acceleration_due_to_gravity = 9.8;
constexpr double moon_gravity = acceleration_due_to_gravity / 6.0;
Such data variables are implicitly const, and must have an initializer which must be a constant expression.
In order to construct constant expression data values from user-defined types, constructors can also be declared with constexpr. A constexpr constructor's function body can only contain declarations and null statements, and cannot declare variables or define types, as with a constexpr function. There must exist argument values such that, after argument substitution, it initializes the class's members with constant expressions. The destructors for such types must be trivial.
The copy constructor for a type with any constexpr constructors should usually also be defined as a constexpr constructor, in order to allow them to be returned by value from a constexpr function. Any member function of a class, such as copy constructors, operator overloads, etc., can be declared as constexpr, so long as they meet the requirements for constexpr functions. This allows the compiler to copy classes at compile time, perform operations on them, etc.
If a constexpr function or constructor is called with arguments which aren't constant expressions, the call behaves as if the function were not constexpr, and the resulting value is not a constant expression. Likewise, if the expression in the return statement of a constexpr function does not evaluate to a constant expression for a particular invocation, the result is not a constant expression. |
|