Major changes worth attention in C ++ 11

Source: Internet
Author: User

Lai Yonghao (http://laiyonghao.com)
Disclaimer: This article is based on the article "the biggest changes in C ++ 11 (and why you shoshould care)" published by Danny Kalev in June 21, 2011. Almost everything has been moved, but not full text photograph translation, there are confusion, please refer to the original article (http://www.softwarequalityconnection.com/2011/06/the-biggest-changes-in-c11-and-why-you-should-care/
).
Note: The author Danny Kalev was a member of the C ++ Standards Committee.

Lambda expressions

Lambda expressions are in the following format:
[Capture] (parameters)-> return-type {body}
Let's look at an example of counting a Character Sequence with several uppercase letters:
Int main () <br/>{< br/> char s [] = "Hello world! "; <Br/> int uppercase = 0; // modified by the lambda <br/> for_each (S, S + sizeof (s), [& uppercase] (char C) {<br/> If (isupper (c) <br/> uppercase ++; <br/> }); <br/> cout <uppercase <"uppercase letters in:" <S <Endl; <br/>}
In [& uppercase], & indicates that the lambda function body needs to obtain an uppercase reference so that it can change its value. If no &, then, uppercase will be passed in the form of passing values.

Automatic type derivation and decltype

In C ++ 03, the object type must be specified when it is declared. In fact, in most cases, the object Declaration also includes an initial value, c ++ 11 in this case, you can stop specifying the type when declaring the object:
Auto x = 0; // 0 is of the int type, so X is of the int type. <br/> auto c = 'a'; // char <br/> auto d = 0.5; // double <br/> auto national_debt = 14400000000000ll; // long
This feature is useful when the object type is large and long, for example:
Void func (const vector <int> & VI) <br/>{< br/> vector <int>: const_iterator CI = VI. Begin (); <br/>}
The iterator can be declared:
Auto CI = VI. Begin ();
C ++ 11 also provides a mechanism to "capture" the type from an object or expression. The new operator decltype can "capture" the type of the result from an expression and "return ":
Const vector <int> VI; <br/> typedef decltype (VI. Begin () cit; <br/> CIT another_const_iterator;

Unified initialization syntax

C ++ has at least four different initialization forms. For example, for initialization in parentheses, see:
STD: String S ("hello"); <br/> int M = int (); // default Initialization
There are also equal signs:
STD: String S = "hello"; <br/> int x = 5;
For the pod set, you can also use braces:
Int arr [4] = {0, 1, 2, 3}; <br/> struct TM today = {0 };
Finally, initialize the constructor:
Struct s {<br/> int X; <br/> S (): x (0 ){}};
So many initialization forms, not only will the cainiao be very big, but the experts cannot afford it. Even worse, Class Members in the pod array cannot be initialized in C ++ 03, or the pod array cannot be initialized when new [] is used! C ++ 11 stands out in braces:
Class C <br/>{< br/> int A; <br/> int B; <br/> Public: <br/> C (int I, Int J ); <br/>}; <br/> C c {0, 0}; // C ++ 11 only. equivalent to C (); <br/> int * A = new int [3] {1, 2, 0 }; /C ++ 11 only <br/> Class X {<br/> int A [4]; <br/> Public: <br/> X (): A {1, 2, 3, 4} {}// C ++ 11, initialize the array member <br/> };
Another good thing is that the container can finally get rid of the push_back () call. In C ++ 11, the container can be initialized intuitively:
// C ++ 11 container initializer <br/> vector vs <string >={ "first", "second", "third "}; <br/> map singers = <br/> {"Lady Gaga", "+ 1 (212) 555-7890" },< br/> {"Beyonce Knowles ", "+ 1 (212) 555-0987 "}};
Data member initialization in the class is also supported:
Class C <br/> {<br/> int A = 7; // C ++ 11 only <br/> Public: <br/> C (); <br/> };

Deleted and defaulted Functions

Functions in the following format:
Struct a <br/>{< br/> A () = default; // C ++ 11 <br/> virtual ~ A () = default; // C ++ 11 <br/> };
It is called the defaulted function, = default; which indicates the default Implementation of the function generated by the compiler. There are two advantages: one is to make the programmer easy, less typing on the keyboard, and the other is to have better performance.
The deletulted function is opposite to the defaulted function:
Int func () = Delete;
A major purpose of this product is to implement noncopyabe to prevent object copying. To Disable copying, declare two key member functions with = deleted:
Struct nocopy <br/>{< br/> nocopy & operator = (const nocopy &) = Delete; <br/> nocopy (const nocopy &) = Delete; <br/>}; <br/> nocopy A; <br/> nocopy B (a); // compilation error. The copy constructor is the deleted function.

Nullptr

Nullptr is a new C ++ keyword, which is a null pointer constant and is used to replace high-risk null macros and 0 literal values. Nullptr is strongly typed:
Void F (INT); // #1 <br/> void F (char *); /// #2 <br/> // C ++ 03 <br/> F (0); // which F is called? <Br/> // C ++ 11 <br/> F (nullptr) // no doubt, the call is #2
Nullptr can be used for all pointers, including function pointers and member pointers:
Const char * Pc = Str. c_str (); // data pointers <br/> If (PC! = Nullptr) <br/> cout <Pc <Endl; <br/> int (A: * PMF) () = nullptr; // pointer to the member function <br/> void (* PMF) () = nullptr; // pointer to the Function

Delegate constructor

The constructor in C ++ 11 can call another constructor of the same class:
Class M // C ++ 11 delegating constructors <br/>{< br/> int X, Y; <br/> char * P; <br/> public: <br/> M (int v): X (V), y (0), P (New char [Max]) {}// #1 target <br/> M (): m (0) {cout <"delegating ctor" <End ;}// #2 delegating
#2 is the so-called Delegate constructor. It calls the real constructor #1.

Right reference

In C ++ 03, the reference type is bound only to the left value. c ++ 11 references a new reference type called the right value reference type, which is bound to the right value, such as a temporary object or literal.
The main reason for adding the right value reference is to implement the move semantics. Unlike traditional copying, moving means that the target object "steals" The resources of the original object and places the source in the "null" state. When copying an object, it is expensive and unnecessary, and the move operation can replace it. For example, when switching strings, moving has a significant performance improvement. For example, the original solution is as follows:
Void naiveswap (string & A, string & B) <br/>{< br/> string temp = A; <br/> A = B; <br/> B = temp; <br/>}
This solution is silly, naive, and very slow, because you need to apply for memory and then copy characters, and move only needs to exchange two data members, without the need to apply for, release the memory and copy the character array:
Void moveswapstr (string & empty, string & filled) <br/>{< br/> // pseudo code, but you get the idea <br/> size_t SZ = empty. size (); <br/> const char * P = empty. data (); <br/> // move filled's resources to empty <br/> empty. setsize (filled. size (); <br/> empty. setdata (filled. data (); <br/> // filled becomes empty <br/> filled. setsize (sz); <br/> filled. setdata (p); <br/>}
To implement a class that supports move, you must declare the move constructor and the move assignment operator as follows:
Class movable <br/>{< br/> movable (movable &); // move constructor <br/> movable & operator = (movable &&); // move assignment operator <br/> };
The C ++ 11 standard library is widely used in the move semantics, and many algorithms and containers have already used the move semantics optimization.

C ++ 11 standard library

In addition to the new containers (unordered_set, unordered_map, unordered_multiset, and unordered_multimap) contained in tr1, there are also some new libraries, such as regular expressions, tuple, and function object wrappers. The following describes some new features of the C ++ 11 Standard Library:

Thread Library

From the programmer's point of view, the most important feature of C ++ 11 is concurrency. C ++ 11 provides the Thread class, promise and future for synchronization in the concurrent environment, and execute concurrent tasks using the async () function template, and thread_local stores the data declared exclusively for a specific thread, where (http://www.devx.com/SpecialReports/Article/38883) has a simple C ++ 11 thread library tutorial (English ).

New smart pointer class

The unique smart pointer class auto_ptr defined by C ++ 98 has been discarded, and C ++ 11 introduces new smart targeting classes shared_ptr and unique_ptr. They are compatible with other components of the standard library. Smart pointers can be securely stored in the standard container, or standard algorithms can be used to "flip" them.

New Algorithm

Mainly all_of (), any_of () and none_of (). The following is an example:
# Include <algorithm> <br/> // C ++ 11 Code <br/> // are all of the elements positive? <Br/> all_of (first, first + N, ispositive (); // false <br/> // is there at least one positive element? <Br/> any_of (first, first + N, ispositive (); // true <br/> // are none of the elements positive? <Br/> none_of (first, first + N, ispositive (); // false
There is also a new copy_n:
# Include <algorithm> <br/> int source [5] = {, 80}; <br/> int target [5]; <br/> // copy 5 elements from source to target <br/> copy_n (source, 5, target );
The iota () algorithm can be used to create an incremental sequence. It first assigns the initial value to * first, then increases the initial value with the frontend ++ operator, and assigns the value to the element pointed to by the next iterator, as shown below:
# Include <numeric> <br/> int A [5] = {0}; <br/> char C [3] = {0 }; <br/> iota (A, A + 5, 10); // Changes A to {10, 11, 12, 13, 14} <br/> iota (C, C + 3, 'A'); // {'A', 'B', 'C '}
Yes, C ++ 11 still lacks some useful libraries such as xml api, socket, Gui, reflection-and automatic garbage collection. However, the existing features have made C ++ more secure and efficient (yes, more efficient, see Google's benchmarking results http://www.itproportal.com/2011/06/07/googles-rates-c-most-complex-highest-performing-language/) and easier to learn and use.
If you think C ++ has changed too much, you don't have to worry about it. Just spend some time learning. You may agree with stroustrup After integrating new features: C ++ 11 is a new language-a better C ++.

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.