const and constexpr

c ++ in constexpr:

  1. Determination compile time and run-time determination: The determination const int a = 3 compile time; determining as const int b = func () is running; wherein a compile-time is determined, b is determined runtime;

    But when the FUNC () function implementation is func () {return 3;}, returns a constant value, this time if received by const, is still determined runtime, if constexpr receiving function return values, constexpr int b = func (); compiler at compile time constant can determine its properties.

    constexpr display tells the compiler that this value is constant. However, if the return of the function func is not constant, constexpr int func () {return func2 ();} func2 variable returns a value, although this time constexpr specified, but the time constant value is still determined to be delayed until run-time.

       The role of constexpr: the constant value information in advance to confirm the constant expression compilation phase.

  2.constexpr modified pointer indicates the top pointers, valid pointer.

    3.c ++ 11 specify the function return value and parameters must be guaranteed to be literal, and only one return, can not be virtual; c ++ 14 with respect to the c ++ 11 do not have to ensure that only one retuan; (a return of the function the return value can be calculated using the ternary operator or a recursive complex situations)

   When const and constexpr modified variables: const expressions can then determine the constant property at run time, a constant determined by the expression constexpr modified attribute (constant value) compiler.

   const and modification functions when constexpr: constexpr constant function parameters can not be determined if the properties in the compiler, the equivalent const

   When const and constexpr modified classes: Although constructors can not be const, but the class constructor literals can be constexpr function. In fact, a literal constant constexpr class must provide at least one constructor.

    constexpr = constructor can be declared as the default form (or in the form of delete function). Otherwise, constexpr constructor must meet the requirements of both the constructor (meaning not contain a return statement), but also to meet the requirements constexpr function (meaning it has only executable statement is the return statement).

    Taking these two points clear, constexpr constructor body in general should be empty, so the initialization of a function member must be placed in the initialization list. constexpr constructor must initialize all data members, constexpr constructor ensures all the parameters passed to it are constexpr type, all members are also generated object constexpr

 

 

Reference Address: https://www.jianshu.com/p/34a2a79ea947  

        https://blog.csdn.net/qq_37653144/article/details/78518071

The following turn:  https://www.cnblogs.com/wangxiaobao/p/5966394.html

 

Scott Meyers在effective modern c++中提到“If there were an award for the most confusing new word in C++11, constexpr would probably win it.”

Thus, constexpr indeed more difficult to understand. Together with its in C ++ 11 standard and 14 are slightly different, but also exacerbate this difficulty.

Reference few of the classic textbook (C ++ primer, effective modern C ++, a tour of C ++) and blue greatly to know some of the answers in the peace, sorting out constexpr usage and precautions.

1. Concept, constexpr objects

Definition of C ++ primer is given in the "constant expression refers to not change and the calculation results can be obtained during compilation expression  [1] ."

Can be understood as a layer applied on const and qualification, i.e. const is not limited to operation of the constant or constants of the compiler , and constexpr must compile-time constant (at compile the results obtained) .

For example as follows:

As we all know, array of size is to be determined at compile time, so when its size is not a constant expression, is not through the compilation.

I int; 
const int size = I; 
int ARR [size]; // error, the expression is not a constant size, can not be determined at compile

If size is a variable constexpr is eligible compile determined by the compiler.

Auto size = 10 constexpr; 
int ARR [size]; // the OK, size constant expressions

Of course, when you want to define a constant expression, we must also ensure that the right side is a constant expression, otherwise there will not compile.

I int; 
constexpr = I int size; // error, can not be determined at compile I

So with effective modern c ++ in one sentence summary is this part:

“constexpr objects are const and are initialized with values known during compilation【2】”.

 

2. constexpr functions

Compared constexpr variables, function constexpr modified some places more easily confused.

. 1) constexpr modified function, when an incoming parameter can be calculated at compile time, generating constexpr variable; when an incoming parameter can not be computed at compile time, generating run traverse (constexpr non-existent) .

Therefore, do not have to write two functions, if the function body exist constexpr applicable conditions, it should be added constexpr keyword.

For example (Example Source [3] ):

Copy the code
int foo constexpr (I int) { 
    return I +. 5; 
} 

int main () { 
    int I = 10; 
    STD :: Array <int, foo (. 5)> ARR; // the OK,. 5 is a constant expression, is calculated foo (5) is a constant expression 
    
    foo (i); // call is Ok, i is not a constant expression, but still can call (constexpr is ignored) 
    
    std :: Array <int, foo (i)> arr1; // Error, but foo (i) call the result is not a constant expression 
   
}
Copy the code

2) C ++ difference between 14 and 11

In C ++ 11 standard, with respect to the constexpr modified function is defined and harsh conditions: the type of function return value and all of the parameter types are literal types, and function in vivo and must have only one return statement [ 1] .

This condition is clearly too harsh, so many operations in constexpr of the aid to be? : Expressions, recursion and other methods to achieve.

In C ++ 14, this defines a relaxed, leaving only the "return value of the function and any type of parameter types are literal types", that is, these values ​​can be determined at compile time on the line.

 

3. constexpr class (class literals)

built-in type is a literal constant, but sometimes you need to customize the type and as literal constant, this time on the need to be modified to constexpr constructor.

Literals constexpr class must provide at least one constructor.

E.g:

Copy the code
class Point {
public:
    constexpr Point(double xval = 0, double yval = 0): x(xval), y(yval) { }
    constexpr double getX() const {return x;}
    constexpr double getY() const {return y;}
private:
    double x,y;
};
Copy the code

When such a class is defined, it may be an object of type Point to define literals. which is:

Copy the code
constexpr Point p1(9.4, 27,7);
constexpr Point p2(28.8, 5.3);

constexpr
Point midpoint(const Point& p1, const Point& p2) {
    return {p1.getX() + p2.getX() / 2, p1.getY() + p2.getY() / 2} ;
}
 
constexpr auto mid = midpoint (p1, p2);
Copy the code

In the above example, p1, p2 are literal constants, midpoint is constexpr modified function, so strike the whole process can be completed mid both at compile time, the software running time will naturally be greatly reduced.

So far on the three main uses constexpr (constexpr variables, constexpr modification function, constexpr modified constructor) on summary is completed, the following are some considerations.

 

Note 1 found that many people (including myself) to verify the example array size must be specified at compile time in gcc::

If the array is defined within a main function, it is not even given a constant expression, can also compiled. This almost subvert my knowledge. . .

Blue greatly in the know almost answer [4] explained this, in fact, is in variable length array C99. Can not be used in a global variable (not allocate memory), may be used in local variables, reference may share details to answer.

Note 2: constexpr so complicated, in the end Why? 

In fact, the first is for efficiency. Efficiency is one of C ++ design philosophy, compile-time to determine what, they can remind compiler optimization, it may be stored in a read-only memory in

The second variable is declared as constexpr can be used in an array such as the length specified above, and includes a template parameters, case labels and so on, will facilitate the use of [5] .

 

References:

1. Stanley B. Lippman / Josée Lajoie / Barbara E. Moo, C ++ Primer Chinese version (Release 5) [M]. Electronic Industry Press, 2013

2. Meyers S. Effective Modern C++[M]. O'Reilly, 2014.

"? The difference between C ++ const and constexpr" 3 know almost blue in the question answer:  https://www.zhihu.com/question/35614219

4. In the blue know "? Constexpr and const array of difference" in question almost answers:  https://www.zhihu.com/question/29662350/answer/45192834

5. Stroustrup B. A Tour of C++[M]. Addison-Wesley Longman, Amsterdam, 2013.

Guess you like

Origin www.cnblogs.com/Zhangyq-yard/p/10959082.html
Recommended