C ++ 11/14 Learning (1) nullptr and constexpr, nullptrconstexpr
I. nullptr
Example:
# Include <iostream>
Voidfoo (char * c ){} Voidfoo (intn ){}
Intmain () { Foo (0 ); // Foo (NULL); // compilation fails Foo (nullptr ); Return 0; }
|
Foo (NULL) cannot be compiled because the compiler does not know which type of parameter NULL is implicitly converted.
Therefore, when NULL is required, you must use nullptr directly.
2. constexpr
The new C ++ 11 standard allows variables or functions to be declared as the constexpr type, and the compiler will verify whether the value of a variable is a constant expression.
The variable declared as constexpr must be a constant and must be initialized using a constant expression.
1. constexpr Modifier
Constexprintsub (inti) { Returni-1; }
Constexprinta = 1; // 1 is a constant expression. Constexprintb = a + 1; // a + 1 is a constant expression. Constexprintsz = sub (B); // sub is a constexpr function, which is a correct statement. Intarr [sub (B)] = {0}; // The Compiler allows this definition and optimizes sub (B) to 1. This was illegal before C ++ 11.
|
2. constexpr modifier class
Constexpr can modify the class Constructor
That is, ensure that all parameters passed to this constructor are constexpr, and all members of the generated object are constexpr.
This object is also a constexpr object, which can be used only when constexpr is used.
** Note ** the function body of the constexpr constructor must be empty and all member variables are initialized in the initialization list.
ClassTest { Public: ConstexprTest (intarg1, intarg2): v1 (arg1), v2 (arg2 ){} Private: Intv1; Intv2; };
ConstexprTest A (1, 2) Enume = {x = A. v1, y = A. v2 }; |
3. constexpr Recursive Function
Constexprintfibonacci (constintn) { Returnn = 1 | n = 2? 1: Maid (n-1) + maid (n-2 ); } |
Starting from C ++ 14, the constexptr function can use simple statements such as local variables, loops, and branches internally.
For example, the following code cannot be compiled under the C ++ 11 standard.
Constexprintfibonacci (constintn) { If (n = 1) return 1; If (n = 2) return 1; Returnfibonacci (n-1) + fig (n-2 ); } |
4. Benefits of using constexpr