C++11 new Features-common

Source: Internet
Author: User

1.auto

Its function is inferred for the type. Auto is a placeholder for a type that informs the compiler to infer the true type of the declared variable based on the initialization code. It can be used for declaring variables in various scopes.

Auto i=;                 // iwas an int auto l=42ll;              // L is a long longauto p=new foo ();      //

When traversing an STL container, you need to declare an iterator (iterator), and now you do not need to declare a typedef to get concise code.

STD::MAP<STD::string,std::vector<int>> map;  for (Auto it = begin (map); it! = end (map); ++it) {}

It is important to note that auto cannot be used to declare the return value of a function, but if the function has a trailing return type, auto can appear in the function declaration where the value is returned. in this case, auto does not tell the compiler to infer the return type, but instead directs the compiler to look for the return value type at the end of the function.

template< TypeName T1, TypeName t2>-decltype (t1 + T2) {    return t1+ C10>23.14);  // V ' s type is double
2.nullptr

It used to represent null pointers, but since 0 can be converted to integers by an implicit type, there are some problems.

void int  ); void Char * p);

If you have both of these methods, c++98 compilation fails when you call F (0), but the F (int) method is called in c++11, and you want to call F (Char *p) as: F (nullptr).

An implicit type conversion can occur between nullptr and any pointer type, as well as null values of the class member pointer type, or it can be implicitly converted to type bool (with a value of false). However, there is no implicit type conversion to an integral type.

for forward compatibility, 0 is still a valid null pointer.

3.rang-based for loops (range-based for loop)

Consider the question: add 1 to each element in the vector<int>.

void int & a) {    1;} int intarray[] = {1,2,3,4,5};vectorint > Intvector (intarray,intarray+5);

The first of the original practices:

 for (vector<int) {    Add (*iter);}

The second type of foreach using boost:

#include <boost/foreach.hpp>boost_foreach (int& a,intvector) {    Add (a) ;}

The third use of For_each:

#include <algorithm>for_each (Intvector.begin (), Intvector.end (), add);

The fourth type is the for statement that C++11 extends:

 for int& e:intarray) {  = e+1;}

with this new notation, you can iterate over the array, the initialization list, and the type of any overloaded non-member begin and end functions.

4.Override and final

The vitual keyword is optional, which makes reading the code a lot more laborious. Because it may be necessary to trace back to the source of the inheritance system to determine whether a method is a virtual function. To increase readability, I always write the virtual keyword in the derived class as well. Even so, there are still some subtle mistakes to be created. So C++11 added two new identifiers.

Override identifier: Specifies that the virtual function in the base class should be overridden.

Final identifier: Specifies that a function in a derived class does not override a virtual function in the base class.

classB { Public:   Virtual voidFint) {Std::cout <<"B::f"<<Std::endl;}};classB | Publicb{ Public:   Virtual voidFint)Override Final{Std::cout <<"D::f"<<Std::endl;}};classF: Publicd{ Public:   Virtual voidFint) {Std::cout <<"F::f"<<Std::endl;}};

The above program will error: "D::f" declared as "final" function cannot be "f::f" rewrite.

5.stong-typed Enums strongly typed enumeration

Traditional C + + enumeration types have some drawbacks: they expose enumeration constants to the outer scope (which can cause name collisions if two different enumeration types exist in the same scope, but with the same enumeration constants conflict), and they are implicitly converted to integers and cannot have a specific user-defined type.

enum A {a, b};        By default, 0 is assigned, followed by 1//enum B {A, c};      Error a redefinition: previously defined as an enumerator
cout << a << "," << B; Output is 0,1

This is fixed by introducing a new type of appellation-strongly-typed enumeration in C++11, which is identified by the keyword enum class. It does not expose enumerated constants to the outer scope or implicitly to integral types, and has a specific type specified by the user.

enum class A {a, b}; enum class B {A, c};   No error //cout << a <<endl;     Error: A undeclared identifier //cout << a::a <<endl;  Error:<< did not find operator cout << (int) that accepts the right operation of type A, a::a <<endl;  Output 0
6.Smart Pointers Smart pointer

1) Unique_ptr: If the ownership of the memory resource does not need to be shared, use this (it has no copy constructor), but it can be transferred to another unique_ptr (there is a move constructor).

voidFooint*p) {Std::cout<< *p <<Std::endl;} Std::unique_ptr<int> P1 (New int( the)); Declares a smart pointer P1, initialized with a value of 42std::cout<< * P1 <<Std::endl; Output 42std::unique_ptr<int> p2 = std::move (p1);//P1 transfer to P2,p1 to empty, automatically frees memory//std::cout << * p1 << Std::endl; Error: The program was interrupted because P1 has been set to emptyStd::cout << p1.Get() << Std::endl; The output for the 00000000,get function returns a nullptrstd::cout<< * P2 <<Std::endl; Output (*P2) + +; P2 pointing to content plus 1if(p2) foo (p2.Get()); Output 43

2) shared_ptr: Use this if the memory resource needs to be shared.

voidFooint*p) {cout<< *p <<Endl;}voidBar (std::shared_ptr<int>p) {    ++(*p);} Std::shared_ptr<int> P1 (newint( the) ); //Declare a smart pointer P2, initialize to std::shared_ptr<int> p2 =P1;                                 //share P1 to P2bar (p1); //Change the value of P1, and also change the value of P2 foo (p2.Get() );//Output is

The first of these statements can also be written as:

Auto P3 = std::make_shared<int>;

Make_shared<t> is a non-member function, and the advantage of using it is that the memory of the shared object and the smart pointer itself can be allocated at once. Instead, the display uses the shared_ptr constructor to construct at least two memory allocations. In addition to the additional overhead, memory leaks can occur. In the following example, seed () throws an error that causes a memory leak.

void foo (std::shared_ptr<int> P,int  init) {    * p = init;} Foo (std::shared_ptr<int> (newint), Seed ());

3) weak_ptr: holds a reference to the object managed by the shared_ptr, but does not change the reference count value. It is used to break the dependency cycle (imagine a tree structure in which a parent node references a child node through a shared ownership reference (CHARED_PTR), and the child node must also hold a reference to the parent node. If these two references also share ownership, it causes a loop and eventually two node memory is not freed.

Auto P = std::make_shared<int> ( the); Std::weak_ptr<int> WP = P;//WP just got the observation right, no shared resourcesAuto SP= WP.Lock();//Lock () obtains an available shared_ptr object from the observed shared_ptrStd::cout << *sp <<Std::endl; P.reset (); //Reset () Destroy function if(Wp.expired ())//expired () ==true means that the object that WP refers to has been destroyedStd::cout <<"Expired"<< Std::endl;
7.Lambdas (anonymous function)

Syntax form: [function object parameter] (operator overloaded function parameter) mutable or exception declaration, return value type {function Body}.

1) Function object parameters are available in the following ways:

Null: No function object parameters are used.

=: The body of the function can use all the visible local variables within the scope of the lambda, and is the way in which the values are passed.

&: The body of a function can use all the visible local variables within the scope of a lambda, and is a reference delivery method.

This: The function body can use a member variable in the same class as lambda.

A: The A is passed by value. When passing by value, the function body cannot modify the copy of a passed in because the function is const by default, and to modify the copy of a passed in, you can add the mutable modifier.

&a: The A is passed by reference.

A,&b: The A is passed by value and B is passed by reference.

=,&a,&b: Except that A and B are passed by reference, other parameters are passed by value.

&,a,b: Except for A and B are passed by value, other parameters are passed by reference.

2) operator overload function parameter: This part can be omitted when there is no parameter. Parameters can be passed by value and by reference to both sides of the test.

3) mutable or exception declaration: This part can be omitted. When you pass a function object parameter by value, you can modify the copy passed in by value when you add the mutable modifier. The exception declaration is used to specify the exception that the function throws, such as an exception that throws an integer type, and you can use throw (int).

4) The return value type: Identifies the type of the function return value. This section can be omitted when the return value is void or where there is only one return in the function body.

5) function Body: Identifies the implementation of the function, this part cannot be omitted, but the function body can be empty.

vector<int> iv{5,4,3,2,1};intA =2, B =1; For_each (Iv.begin (), Iv.end (), [b] (int&AMP;X) {cout<< (x + b) <<endl;});//Output 6 5 4 3 2For_each (Iv.begin (), Iv.end (), [=] (int&x) {x *= (a + b);});//IV multiply each number by 3
For_each (Iv.begin (), Iv.end (), [] (int &x) {Cout<<x<<endl;}); //Output 9 6 3 For_each (Iv.begin (), Iv.end (), [=] (int&AMP;X)int{returnX * (A + b);});//Only returns 3 times times of each number, but does not change the number of the original array
For_each (Iv.begin (). Iv.end (), [] (int &x) {Cout<<x<<endl;}) ; //output is 9 6

One more example:

std::vector<int>V;v.push_back (1); V.push_back (2); V.push_back (3); Std::for_each (Std::begin (v), Std::end (v), [] (intN) {std::cout << n <<Std::endl;}); //Output is 1 2 3 auto is_odd= [](intN) {returnn%2==1;}; //define a function is_odd, return 1 (not be able to be 2 integers) or 0 (can be 2 integers)Auto pos=std::find_if (Std::begin (v), Std::end (v), is_odd); //find_if The data for the Finder and the condition, and returns a pointer to the data if(POS! =Std::end (v)) Std::cout<< *pos << Std::endl;//The first qualifying data is 1 and the output is 1

More complex is the recursive lambda.

std::function<int(int) > LFIB = [&lfib] (int n) {return21 : Lfib (n1) + LFIB (n-2);}; cout<<lfib (5) <<endl;;

(temporarily updated here, follow-up will continue to update)

C++11 new Features-common

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.