C + + 11 new features

Source: Internet
Author: User
Tags garbage collection thread class

Rai Yonghao (http://laiyonghao.com)
Disclaimer: This article derives from the article "the biggest Changes in c++11 (Why)", published by Danny Kalev on June 21, 2011, and almost all of the content has been moved, but not translated in full, and there is confusion , please refer to the original text (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 Expression

The form of a LAMBDA expression is this:

[Capture] (parameters)->return-type {body}  

Take a look at some examples of several uppercase letters in a sequence of characters:

int main ()  
{  
   char s[]= "Hello world!";  
   int uppercase = 0; Modified by the Lambda  
   for_each (S, s+sizeof (s), [&uppercase] (char c) {  
    if (Isupper (c))  
     uppercase++;< c8/>});  
 cout<< uppercase<< "uppercase letters in:" << s<<endl;  
}  
The meaning of & in [&uppercase] is that the lambda function body gets a uppercase reference so that it can change its value, and if not, then uppercase passes the past in the form of a pass value.

automatic type inference and Decltype

In c++03, declaring an object must also indicate its type, and in most cases, declaring an object also includes an initial value, in which case the C++11 can let you declare the object without specifying the type:

Auto x=0;  0 is int type, so x is also int type  
auto c= ' a ';//char  
auto d=0.5;//double  
Auto National_debt=14400000000000ll;//long Long  

This feature is useful when the type of the object is very large, such as:

void func (const vector<int> &vi)  
{  
  vector<int>::const_iterator ci=vi.begin ();  
}  

The iterator can be declared as:

C++11 also provides a mechanism for "capture" types from objects or expressions, and a new operator Decltype can "capture" the type of its result from an expression and "return":
const vector<int> VI;  
typedef decltype (Vi.begin ()) CIT;  
CIT Another_const_iterator;  

Unified Initialization Syntax

C + + has at least 4 different initialization forms, such as initialization in parentheses, see:

std::string s ("Hello");  
There is also an equal form:
std::string s= "Hello";  
int x=5;  
For POD collections, you can also use curly braces:
int arr[4]={0,1,2,3};  
struct TM today={0};  
Finally, members of the constructor are initialized:
struct S {  
 int x;  
 S (): X (0) {}};  
So many initialization forms, not only the rookie will make a big head, master also unbearable. What's worse is that c++03 cannot initialize class members of POD arrays, nor can the initial pod array when using new[], motherfucker. C++11 is eminence with braces:
Class C  
{  
int A;  
int b;  
Public:  
 C (int i, int j);  
C c {0,0}; C++11 only. Equivalent to C C (0,0);  
int* a = new Int[3] {1, 2, 0}; /c++11 only  
class X {  
  int a[4];  
Public:  
  X (): a{1,2,3,4} {}//c++11, initializing array member  
};  
Another good thing is that for the container, you can finally get rid of the push_back () call, the C++11 can visually initialize the container:
c++11 container initializer  
vector vs<string>={"A", "second", "Third"};  
Map singers =  
  {"Lady Gaga", "+1 (212) 555-7890"},  
    
The data member initialization in the class is also supported:
Class C  
{  
 int a=7;//c++11 only public  
:  
 C ();  
};  

deleted functions and defaulted functions

Functions like the following form:

struct a  
{  
 a () =default;//c++11  
 virtual ~a () =default;//c++11  
};  
Called defaulted function, =default; Instructs the compiler to generate the default implementation of this function. There are two advantages: one is to make the programmer easy, less to knock on the keyboard, and the other is to have better performance.
The opposite of the defaulted function is the deleted function:
int func () =delete;  
This product has a large use is to implement Noncopyabe to prevent the copying of objects, in order to prohibit copying, with =deleted to declare two key member functions on it:
struct nocopy  
{  
    nocopy & operator = (const nocopy &) = delete;  
    Nocopy (const nocopy &) = delete;  
Nocopy A;  
Nocopy B (a); Compilation error, copy constructor is deleted function  

nullptr

Nullptr is a new C + + keyword, which is a null pointer constant, which is used to replace high risk NULL macros and 0 literal quantities. Nullptr are strongly typed:

void f (int); #1  
void F (char *);//#2  
//c++03  
f (0);//What f is called?  
C++11  
F (nullptr)//No doubt, the call is #2  
All the pointers can be nullptr, including function pointers and member pointers:
const char *PC=STR.C_STR (); Data pointers  
if (pc!=nullptr)  
  cout<<pc<<endl;  
Int (A::* PMF) () =nullptr; Pointer  
Void (*PMF) () pointing to a member function =nullptr;//Pointer to function  

Delegate Constructors

A constructor in C++11 can call another constructor of the same class:

Class M//c++11 delegating constructors  
{  
 int x, y;  
 char *p;  
Public:  
 m (int v): X (v), y (0),  p (new char [MAX])  {}//#1 target  
 m (): M (0) {cout<< "Delegating ct or "<<end;} #2 Delegating  
#2 is called a delegate constructor that invokes the real constructor #1.

Right Value reference

The reference type in c++03 is bound to only the left value, and c++11 refers to a new reference type called the right value reference type, which is bound to a right value, such as a temporary object or literal amount.
The main reason to increase the right value reference is to implement move semantics. Unlike traditional copies, move means that the target object "steals" the resources of the original object and places the source in an "empty" state. When you copy an object, it is expensive and unnecessary, and the move action replaces it. In the case of string swapping, there is a tremendous performance boost with move meaning, as the original scenario would be:

void Naiveswap (String &a, string & B)  
{  
 String temp = A;  
 a=b;  
 b=temp;  
}  

This is silly, naïve, slow, because you need to request memory and then copy the characters, and move only needs to exchange two data members without requesting, freeing memory, and copying character arrays:
void Moveswapstr (string& empty, string & filled)  
{  
//pseudo code, but you get the idea  
 size_t sz=empty . Size ();  
 const char *p= empty.data ();  
Move filled ' s empty  
 empty.setsize (Filled.size ());  
 Empty.setdata (Filled.data ());  
Filled becomes empty  
 filled.setsize (SZ);  
 Filled.setdata (P);  
}  


To implement a class that supports move, you need to declare the move constructor and the move assignment operator as follows:
Class movable  
{  
movable (movable&&),//move constructor movable&& operator=  
(movable &&); Move assignment operator  
};  

C++11 's standard library uses move semantics extensively, and many algorithms and containers have been optimized using move semantics.

C++11 's standard library

In addition to the new containers contained in TR1 (Unordered_set, Unordered_map, Unordered_multiset, and Unordered_multimap), there are new libraries, such as regular expressions, tuple, function object wrappers, and so on. Here are some c++11 new features of the standard library: line Threading

From a programmer's point of view, the most important feature of c++11 is concurrency. C++11 provides a thread class, also provides promise and future for synchronization in a concurrency environment, performs concurrent tasks with the async () function template, and thread_local stores data declared as exclusive to a particular thread, here (http://www.devx com/specialreports/article/38883) has a simple c++11 line threading Tutorial (English). new smart pointer class

The only smart pointer class Auto_ptr defined by c++98 has been deprecated, C++11 introduced new smart-targeted classes shared_ptr and unique_ptr. They are compatible with other components of the standard library, securely storing smart pointers in standard containers, and securely "turning" them in with standard algorithms. the new algorithm

Mainly all_of (), any_of () and none_of (), here are examples:

#include <algorithm>  
//c++11 code//are All of the  
elements positive?  
All_of (First+n, ispositive ()); False  
//is There at least one positive element?  
Any_of (First+n, ispositive ());//true  
//are none of the elements positive?  
None_of (First+n, ispositive ()); False  

There is also a new copy_n:

#include <algorithm>  
int source[5]={0,12,34,50,80};  
int target[5];  
Copy 5 elements from source to target  
copy_n (source,5,target);  

The Iota () algorithm can be used to create an incremental sequence that first assigns the initial value to *first, and then increments the initial value with the Forward + + operator and assigns it to the element that the next iterator points to, as follows:

#include <numeric>  
int a[5]={0};  
Char c[3]={0};  
Iota (A, a+5, 10); Changes a to {10,11,12,13,14}  
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, you can see Google's benchmark results http://www.itproportal.com/2011/06/07/ googles-rates-c-most-complex-highest-performing-language/) and easier to learn and use. If you feel that C + + changes are too big, don't panic, spend some time to learn. Perhaps after you have come to the new features, you will agree with Stroustrup's view that c++11 is a new language-a better C + +.

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.