A brief summary of new features of C++11 (ii) _c language

Source: Internet
Author: User

1. Scope for statement

C++11 introduces a simpler for statement that can easily traverse all elements of a container or other sequence

Vector<int> VEC = {1,2,3,4,5,6};
for (int X:vec)
{
  cout<<x<<endl;
}

2. End return type

To introduce a trailing type, we have to start with a complex type declaration. If we need to define an array that contains 10 int elements, this is usually the case:

int arr[10] = {0};

What if you want to define a pointer to this array:

Copy Code code as follows:

int (*p_arr) [+] = &arr; Note: int *p_arr[10] represents an array with 10 elements, and the element type is int*

If you are defining a function, this function takes a parameter of type char and returns a pointer to an array of 10 int types:

Copy Code code as follows:

Int (*func (char x)) [10];

This statement is not to see the head is big, in fact, we can simplify a little, in general, we can use aliases for simplification, such as:

Copy Code code as follows:

typedef int ARR[10]; Define a type arr this is an array type that contains 10 elements of type int
Using ARR = int[10]; Ditto

Then define the function as above:

Copy Code code as follows:

ARR * Func (char x); The type returned by the function is arr*, which points to a pointer with an array of 10 int elements

Of course in c++11 we can use another keyword that we've talked about before Decltype:

Copy Code code as follows:

Decltype (arr) * func (char x); Decltype (arr) expressions get the type of arr

And finally, it's our turn to the c++11. Another feature of the end-return type is that any function can use the end-return type, which is most effective for functions that are more complex to return types, such as the following functions can be used:

Copy Code code as follows:

Auto Func (char x)-> Int (*) [10];

This form writes the return type of the function to the last side of the function declaration, with the-> symbol appended to the function parameter list, followed by the type that the function needs to return, and a auto substitution is used before the function name because the return type of the function is placed behind the parameter list.

3. =default generate default constructor

In the C + + class, if we do not define a constructor, the compiler will synthesize the default parameterless constructor for us, and if we define a constructor, then the compiler will not generate a default constructor, but what if we define the constructor and want the compiler to generate the default constructor? C++11 can require the compiler to generate constructors by directly =default in the declaration of a constructor.

Class classname{public
  :
    ClassName (int x);
    ClassName () =default; Display requires compiler build constructor
};

4. Class object member Class

Class ClassName
{public
    :
        int x =//c++11 is not allowed before
};

5. Lambda expressions and BIND functions

A lambda expression is a unit of code that can be invoked, equivalent to an inline function, with parameters and return values, and a function body. But unlike a function, a lambda expression can be defined inside a function, and a complete lambda expression has the following form:

[Capture List] (argument list) mutable-> return type {function Body}

int x = ten;
int y =;
Auto F = [x,&y] (int a, int b) {++y;return a+b+x+y;};
Cout<<f (1,2) <<endl;
cout<<y<<endl;   21st

A lambda can omit a list of arguments (if there are no arguments), but you can omit the return type, but you cannot omit the capture and function parts, even if the capture list is empty, there is an empty [],lambda there are two kinds of captures, one is value capture, the other is reference capture. If it is a value capture then the lambda gets a copy of the captured variable, if the reference capture is a reference, you can modify the value of the referenced variable inside the lambda, as above x is the value capture, Y is the reference capture, and the lambda is the default value capture, if the variable is previously added & is a reference capture, and in addition there are two forms of reference capture in the lambda, for example, [=] means that the value captures all the visible variables, while [ampersand] means that the reference captures all the visible variables. If you want the value to capture all the visible variables, but there are individual variables that take a reference capture, [=,&x] means that the value captures all the visible variables and references capture X. [&,x] means that the reference captures all visible variables, and X takes the form of value capture.

With the bind function, in many places we can use functions to replace lambda expressions, after all, if the same lambda expression is needed in many places, and if the lambda expression is longer, it should be best to define it as a function. For lambda expressions that do not have a capture list, we can use function substitution directly, for example:

void Main ()
{
  auto f=[] (int x,int y) {return x+y};
  f ();
}

We can replace it in the following way:

int f (int x,int y)
{return
  x+y;
}
 
void Main ()
{
  f ();
}

is equivalent to the lambda above, but what about a lambda expression with a capture list, for example:

void Main ()
{
  int x = ten;
  int y =;
  Auto F = [x,&y] (int a, int b) {return a+b+x+y;}; A value capture, a reference capture
  f (33,44);
}

If the form is converted into a function:

int x = ten;
int y =;
int f (int a,int b)
{return
 a+bx+y;
}
 
void Main ()
{
  F (33,44);
}

This is a feasible approach, but it is not always possible to define all the capture variables as global variables. The key problem now is that the contents of the Lambda capture expression are converted into functions that are not, and C++11 provides the bind function to do so.

#include <functional>//bind ()
#include <iostream>
using namespace std;
Using namespace std::p laceholders; _1,_2 is in the namespace
int f (int x,int y,int a,int b)
{return
 a+b+x+y;
}
 
void Main ()
{
 int x = ten;
 int y =;
 
 Auto F_wrap = bind (f,x,y,_1,_2);
 Cout<<f_wrap (33,44) <<endl; _1,_2 is a placeholder that indicates that the f_wrap is invoked when _1 is the first parameter, and _2 is the second parameter. will eventually be replaced with the call F (10,20,33,44)
}

If the reference type captures how to do this, look at the example below, with a lambda:

#include <iostream>
#include <functional>
using namespace std;
Using namespace std::p laceholders;
void Main ()
{
 int x = ten;
 Ostream &o = cout;
 Auto F =[&o] (int a) {o<<a<<endl;}; Note that the output object here is using a reference capture
 f (x);
}

Using BIND is the case:

#include <iostream>
#include <functional>
using namespace std;
Using namespace std::p laceholders;
void f (ostream &o,int x)
{
 o<<x<<endl;
}
int main ()
{
 int x = ten;
 Auto F_wrap = bind (F,ref (cout), _1); Passing a reference to a variable to bind is an issue, for which C++11 provides a ref () function to obtain a reference
 f_wrap (x);
 return 0;
}

6. Smart pointer share_ptr,unique_ptr

Several smart pointers are introduced in c++11, and the smart pointer can automatically release the object to which it is directed, where shared_ptr allows multiple pointers to be directed to the same object, unique_ptr the object to which it is directed, and we mainly describe the use of shared_ptr. Generates a smart pointer object by using the Make_shared<type> () function.

Copy Code code as follows:

Shared_ptr<int> p = make_shared<int> (40); P points to an int object with a value of 40
shared_ptr<string> P2 = make_shared<string> (a ' C '); String object with value ' CCCCCCCCCC '

The value passed in the make_shared<type> () function matches the constructor of the corresponding type, and should actually be the constructor of the corresponding type that is called directly.

We can initialize the smart pointer with the new initialized pointer:

Copy Code code as follows:

Share_ptr<int> p (new int (40));
P.get (); Use the share_ptr<type> get () function to obtain its associated raw pointer.

The Shared_ptr object, when it leaves its scope (for example, a function body), automatically frees the dynamic memory that its associated pointer points to, just as a local variable does. Many other shared_ptr can point to an object, destroying the dynamic memory of the object associated with it when the last Shared_ptr object is destroyed. A reference count is used here.

7. Right value reference and move call, moving constructor

In order to support move operations, a type called a right value reference is used in c++11. What is a move operation, usually when we assign an object to another object, we invoke the object to the copy constructor or the copy assignment operator. The move constructor and the move assignment operator are used to move data from one object to another object. In many cases the object will need to be destroyed after it is copied, and using the move operation can dramatically improve performance. After the right value reference is used, its associated object is destroyed. The right value reference uses two && representations, for example int && represents the right value reference, and int & is the left value. The function Std::move () provided by the C++11 Standard library gives you a reference to the right value of an object.

Copy Code code as follows:

Testclass::testclass (TestClass &&t) noexcept//Move constructors should not throw any exceptions
: X (T.x), Y (T.Y), Z (t.z), P (T.P)
{
T.p=nullptr; After the move operation is implemented, it is necessary to ensure the destructor of the moved object is secure, so the pointer member of the source object is null, then the destructor of T is called automatically and T is destroyed.
}

8. function

A standard library type named function is provided in c++11, defined in header file <functional>, which stores a callable object, unifying all invocation forms that can be called like functions, such as:

#include <functional>
#include <iostream>
using namespace std;
 
int add (int x,int y)
{return
  x+y;
}
 
Class Add
{public
  :
    int operator () (int x,int y)
    {return
      x+y;
    }}
;
the parameters of the void main () {
 //function template are the form of a function call, including the return type, and the number and type of argument lists
  Function<int (int,int) > f1 = add;// function pointer
  function<int (int,int) > F2 = ADD ();//Callable Class object
  Function<int (int,int) > F3 = [] (int x,int y) { return x+y;}; Lambda expression
   
  cout<<f1 (10,20) << "" <<f2 (30,40) << "" <<f3 (50,60) <<endl;
}

9. Other new types (Array,forward_list,bitset,regex)

In fact, some new libraries are added to the c++11 in addition to some syntax features. For example, an array is the equivalent of a fixed-length array we traditionally use, supports random access, cannot add deletion elements, cannot grow like a vector, and is more secure than traditional arrays using array.

Forward_list is an added one-way list of c++11

Regex is the new regular expression library in c++11

10. Summary

C++11 added some libraries, the use of the library itself does not do too much introduction, you can refer to the C + + standard library/stl source analysis, this is a separate tome to explain, some features and the library is I feel more stunning, such as:

    1. Auto Definition: Allows the compiler to automatically extrapolate the defined variable type without having to write a long string of types, especially on types that contain iterators.
    2. Decltype: You can define a type that is the same as the variable based on a known variable.
    3. Lambda: Personally, this is one of the most stunning features added to the c++11, with the bind () function, which is actually from boost.
    4. Smart pointers: shared_ptr Although there are smart pointers similar to auto_ptr in previous C + +, there are some flaws in auto_ptr that are not very useful.
    5. Function Type: The function type of the standard library defines a callable object that unifies all of the invocation forms that can be called as functions, such as lambda, function pointers, overloaded class objects such as function call operators (), and this feature also refers to the boost library.
    6. Regex Library: C++11 finally has a convenient regex to use.

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.