"Cocos2d-x Game development" cocos2d-x the common c++11 knowledge in the development of small numbers

Source: Internet
Author: User

Since the beginning of cocos2d-x3.0, COCOS2DX has formally used the C++11 standard. The simplicity and convenience of c++11 greatly improves the scalability and maintainability of the program, and also improves the writing speed of the code.

Let's take a look at the c++11 knowledge that cocos2d-x development has to learn.

1. Initialize the list

  Pod structures or arrays can be initialized to simplify code by using an initialization list, based on the order in which members are defined within the structure.

   

struct structa{    int  A;     int b;}; Structa sa={1,2};

In c++03, non-pod-structured classes or STL containers do not support this simple notation, and C++11 provides strong support. You can use Std::initializer_list to let classes and normal functions use the initialization list, and the STL container can also use an initialization list, which is the following code:

 //  class uses the initialization list    classa{ public  : ClassA (std::initializer_list  <int  > list) {}}; ClassA a  = {1 , 2 , 3  };  /*   note! Using std::initializer_list requires the Include <initializer_list> header file  */ 
 //  function Use initialization list   func (std::initializer_list<float  > list) { /*  function Body  */ }func ({ 1.6f , 2.8f  }); 
/* note! Using std::initializer_list requires the Include <initializer_list> header file */
// STL standard container uses initialization list vector<string> s = {"hello","C + +  ","one"};

You can see that after introducing the Std::initializer_list feature, the initialization of variables is a lot simpler and very convenient.

2. Automatic type deduction

Type deduction can automatically identify the type of object at compile time, thus simplifying the code, and using the Auto keyword to automatically deduce type-specific variables, such as:

  

    /* Automatic type deduction */     vector<int> v;    Vector<int>::iterator it=v.begin ();        // Before using type derivation    Auto It2 = V.begin ();                    // after using type derivation

Decltype can also automatically recognize the type based on an existing object, but it differs from auto in that auto derives the type of the right of the expression, and Decltype automatically infers the type of any variable and can use that type to define the variable, which is more difficult to understand. Look at the following code at a glance:

  

    int num;     5;

3. Automatic Range Deduction

  Before C++11, writing a looping statement is usually the case:

  

     for (int0; i++) {            // Use automatic range deduction before        cout << i << endl;    }

In C++11, the For statement adds the syntax for a range iteration that simplifies the code for the For loop, which is the type of element to be programmed to the left of the ":" symbol, which can be a reference or a const reference type, while ":" To the right is the container for the calendar to be an array or an STL container, as follows:

  

    int 1 2 3 4      5 }; // After using automatic range deduction     for (int &i:arr) {        << i << endl;    }

4. Smart pointers and null pointers

A smart pointer is a class rather than a normal pointer, and shared_ptr is a reference counting pointer, and a shared_ptr destroys an object only if no other shared_ptr points to the object it originally pointed to.

In addition to shared_ptr, there are weak_ptr, but weak_ptr does not have the object it points to, so it does not affect the destruction of the object or the weak_ptr, and can only determine if the pointer has been destroyed. Here's an example to illustrate shared_ptr:

  

    /*smart pointers and null pointers*/    //Smart pointers can only be assigned by smart pointers and cannot be shared_ptr<int> pq= new int;shared_ptr<int> P1 (New int); //Enter a new scope with {}    {        //The new smart pointer points to P1, which is the equivalent of one retain to an int memory blockshared_ptr<int> p2 =P1; *P2 =123; //P2 is destroyed, which is equivalent to one release of an int memory block, but because P1 also points to that memory, the reference counter is not 0 and therefore does not release    }    return 0; //The P1 is also destroyed, and the memory occupied by the reference count of 0,int is automatically recycled    /*Watch out! Using shared_ptr requires include <memory>*/

If SHARE_PTR is defined as a member variable of a class, then the retain reference of this smart pointer is released when the object is released.

The existence of NULL pointer nullptr is to solve the two semantic problem of NULL, because NULL can also represent the type of 0,nullptr as nullptr_t, can be implicitly converted to any pointer or a type of member pointer, and they can be compared with equal or unequal. Nullptr cannot be implicitly converted to an integer, nor can it be compared with integers.

  

    void foo (char *);     void foo (int);    Foo (NULL);         // the call is void foo (int);    Foo (nullptr);    void foo (char *);

5.LAMBDA Features

  Lambda expressions are a great new feature, and when you need to add a new temporary function to your program, using the lambda function directly will make you feel that the original write program is still so cool (similar to the anonymous inner class in Java). The lambda notation is as follows:

  

[function external object parameter] (function parameter), return value type {function Body}

(1) The function external object parameter in the function body is allowed to directly call parameters outside the function;

(2) The parameters in the () are not different from the parameters of the normal function, which are the variables passed in each function call;

(3) followed by the type of function return value;

(4) {} You can write logical functions and use [] and () parameters passed in

A parameter reference that defines the same scope as a lambda function can also be used, which is generally called a closure, and [] can be filled in with the following types of parameters, which define the variables in the scope of the lambda function into the body of the function.

1.[] can have no parameters, in which case no external parameters are passed in

2.[A,&B] Passing in the value of variable A and the reference to variable B

3.[&] Pass in all variables in a quoted way

4.[=] Pass all the variables in a value that cannot be modified

5.[&,a] In addition to a in the way of passing values, other variables have been referenced in the way passed in

6.[=,&a] Except that a is passed in as a reference, the other variables are passed in as a value

Let's take a look at an example of how a "=" parameter is used in a lambda, and an assignment to a reference parameter or an external parameter results in an unexpected result, and you need to be aware of the life cycle of the reference object when using "&".

  

    /*lambda expression*/    intB, C, D; Auto Func0= [&] ()void{b =1; c =2; D =3; }; Auto Func1= [=] ()int{return 2*3; }; Auto Func2= [=, &b, &c] ()void{++b; c + = d +b;}; Auto Func3= [=] ()int{returnB +D;};    FUNC0 (); //b,c,d, respectively, ofC=func1 ();//c=6Func2 ();//b=2;c=858993456,d=6;b = func3 ();//b=1717986916    return 0;

When a lambda is defined in a member function of a class, lambda can call the private function of the class, and when the lambda invokes the member function of the class, the member variable or other member function needs to be passed in, = and & will pass in this.

Using Std::function, you can store lambda functions, such as function<void () > to store func0, func1 with Function<int () >, functions with parameters that can be directly in () Input parameter type, include the header file functional when using function.

  

    #include <functional>    function<void() > f1 = func0;    function<int() >f2 = func1;    

Function can also be used to hold normal functions, static functions and public member functions of a class, and the first two, like the use of lambda, directly assign the function name to the functions object (which cannot recognize the overloaded function), but the member functions of the class need to bind using bind:

  

    New ClassA ();    function<void(int) > F2 = Bind (&classa::memberfunc1,obj,std::p laceholders::_1 );    function<void(intchar) >f3 = Bind (&CLASSA::MEMBERFUNC2,OBJ,STD:: Placeholders::_2);

Using the BIND function to bind member functions and object pointers, use the std::p laceholders placeholder to denote the number of arguments for the function, followed by the 1~n.

6. Explicit virtual-function overloading

  Override ensures that when you override a virtual function of a parent class, you adjust the virtual function of the parent class (change the name or argument), you do not forget to adjust the virtual function of the subclass. At compile time, the compiler checks to see if its parent class has the virtual function for a virtual function that is marked as override:

classb{ Public:    Virtual voidVirtuaalfunc (int);};classc{ Public:    Virtual voidVirtuaalfunc (int)Override;//Show overriding parent virtual functions    Virtual voidVirtuaalfunc (Char)Override;//Error};

Final can guarantee that a subclass cannot override a function, cannot have a function with the same signature, or that a class cannot be inherited. (similar to final usage in Java) Override and final are not c++11 keywords, but have special meanings in specific locations and are still used as variables elsewhere.


Horse Lad
Source: http://www.cnblogs.com/msxh/p/5869992.html
Please respect the results of other people's work, let the sharing become a virtue, welcome reprint. In addition, the article in terms of presentation and code, if there is something wrong, welcome
Criticize. Leave your footprints and welcome the comments!

"Cocos2d-x Game development" cocos2d-x the common c++11 knowledge in the development of small numbers

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.