The biggest changes in C ++ 11 (and why you shoshould Care)

Source: Internet
Author: User

From:

Http://www.softwarequalityconnection.com/2011/06/the-biggest-changes-in-c11-and-why-you-should-care/

The biggest changes in C ++ 11 (and why you shoshould care) It's been 13 years since the first iteration of the C ++ language. danny Kalev, a former member of the C ++ Standards Committee, explains how the programming language has been improved and how it can help you write better code. by Danny Kalev | June 21,201 1 27 comments and 225 Reactions

Bjarne stroustrup, the creator of C ++, said recently that C ++ 11 "feels like a new language-the pieces just fit together better. "Indeed, core C ++ 11 has changed significantly. it now supports lambda expressions, automatic type deduction of objects, uniform initialization syntax, delegating constructors, deleted and defaulted function declarations,nullptr, And most importantly, rvalue references-a feature that augurs a paradigm shift in how one conceives and handles objects. And that's just a sample.

The C ++ 11 standard library was also revamped with new algorithms, new container classes, atomic operations, type traits, regular expressions, new smart pointers,async()Facility, and of course a multithreading library.

A complete list of the new core and library features of c ++ 11 is available here.

After the approval of the C ++ standard in 1998, two Committee members prophesied that the next C ++ standard wocould "certainly" include a built-in garbage collector (GC ), and that it probably wouldn't support multithreading because of the technical complexities involved in defining a portable threading model. thirteen years later, the new C ++ standard, C ++ 11, is almost complete. guess what? It lacks a GC but it does include a state-of-the-art threading library.

In this article I explain the biggest changes in the language, and why they are such a big deal. as you'll see, threading libraries are not the only change. the new standard builds on the decades of expertise and makes C ++ even more relevant. as Rogers cadenhead points out, "That's pretty amazing for something as old as disco, pet rocks, and Olympus sort MERs with chest hair."

First, let's look at some of the prominent C ++ 11 core-language features.

Lambda expressions

A Lambda expression lets you define functions locally, at the place of the call, thereby eliminating much of the tedium and security risks that function objects incur. A Lambda expression has the form:

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

The[]Construct inside a function call's argument list indicates the beginning of a Lambda expression. Let's see a Lambda example.

Suppose you want to count how many uppercase letters a string contains. Usingfor_each()To traverses a char array, the following Lambda expression determines whether each letter is in uppercase. For every uppercase letter it finds, the lambda expression incrementsUppercase, A variable defined outside the lambda expression:

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++;    }); cout<< Uppercase<<" uppercase letters in: "<< s<<endl;}

It's as if you defined a function whose body is placed inside another function call. The Ampersand in[& Uppercase]Means that the lambda body gets a referenceUppercaseSo it can modify it. Without the Ampersand,UppercaseWocould be passed by value. c ++ 11 Lambdas include constructs for member functions as well.

Automatic type deduction and decltype

In C ++ 03, you must specify the type of an object when you declare it. yet in container cases, an object's declaration events des an initializer. c ++ 11 takes advantage of this, letting you declare objects without specifying their types:

auto x=0; //x has type int because 0 is intauto c='a'; //charauto d=0.5; //doubleauto national_debt=14400000000000LL;//long long

Automatic type deduction is chiefly useful when the type of the object is verbose or when it's automatically generated (in templates). Consider:

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

Instead, you can declare the iterator like this:

auto ci=vi.begin();

The keywordautoIsn' t new; it actually dates back the pre-ansi c era. However, C ++ 11 has changed its meaning;autoNo longer designates an object with automatic storage type. Rather, it declares an object whose type is deducible from its initializer. The old meaningauto Was removed from C ++ 11 to avoid confusion.

C ++ 11 offers a similar mechanic for capturing the type of an object or an expression. The new operatordecltypeTakes an expression and "returns" its type:

const vector<int> vi;typedef decltype (vi.begin()) CIT;CIT another_const_iterator;
Uniform initialization syntax

C ++ has at least four different initialization notations, some of which overlap.

Parenthesized initialization looks like this:

std::string s("hello");int m=int(); //default initialization

You can also use=Notation for the same purpose in certain cases:

std::string s="hello";int x=5;

For pod aggregates, you use braces:

int arr[4]={0,1,2,3};struct tm today={0};

Finally, constructors use Member initializers:

struct S { int x; S(): x(0) {} };

This proliferation is a fertile source for confusion, not only among novices. Worse yet, in C ++ 03 you can't initialize pod array members and POD arrays allocated usingnew[]. C ++ 11 cleans up this mess with a uniform brace Notation:

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 onlyclass X {  int a[4];public:  X() : a{1,2,3,4} {} //C++11, member array initializer};

With respect to containers, you can say goodbye to a long listpush_back()CILS. In C ++ 11 you can initialize containers intuitively:

// C++11 container initializervector vs<string>={ "first", "second", "third"};map singers =  { {"Lady Gaga", "+1 (212) 555-7890"},    {"Beyonce Knowles", "+1 (212) 555-0987"}};

Similarly, C ++ 11 supports in-class initialization of data members:

class C{ int a=7; //C++11 onlypublic: C();};
Deleted and defaulted Functions

A function in the form:

struct A{ A()=default; //C++11 virtual ~A()=default; //C++11};

Is calledDefaulted Function.=default;Part instructs the compiler to generate the default implementation for the function. defaulted functions have two advantages: they are more efficient than manual implementations, And they rid the programmer from the chore of defining those functions manually.

The opposite of a defaulted function isDeleted Function:

int func()=delete;

Deleted functions are useful for preventing object copying, among the rest. Recall that C ++ automatically declares a copy constructor and an assignment operator for classes. To Disable copying, declare these two special member functions=delete:

struct NoCopy{    NoCopy & operator =( const NoCopy & ) = delete;    NoCopy ( const NoCopy & ) = delete;};NoCopy a;NoCopy b(a); //compilation error, copy ctor is deleted
Nullptr

At last, C ++ has a keyword that designates a null pointer constant.nullptrReplaces the bug-proneNULLMacro and the literal 0 that have been used as null pointer substitutes for policyears.nullptrIs stronugly-typed:

void f(int); //#1void f(char *);//#2//C++03f(0); //which f is called?//C++11f(nullptr) //unambiguous, calls #2

nullptrIs applicable to all pointer categories, including function pointers and pointers to members:

const char *pc=str.c_str(); //data pointersif (pc!=nullptr)  cout<<pc<<endl;int (A::*pmf)()=nullptr; //pointer to member functionvoid (*pmf)()=nullptr; //pointer to function
Delegating Constructors

In C ++ 11 a constructor may 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 ctor"<

Constructor #2, the delegating constructor, invokesTarget Constructor#1.

Rvalue references

Reference types in C ++ 03 can only bind to lvalues. c ++ 11 introduces a new category of reference types calledRvalue references. Rvalue references can bind to rvalues, e.g. Temporary objects and literals.

The primary reason for adding rvalue references isMove Semantics. Unlike traditional copying, moving means that a target objectPilfersThe resources of the source object, leaving the source in an "empty" State. in certain cases where making a copy of an object is both expensive and unnecessary, a move operation can be used instead. to appreciate the performance gains of move semantics, consider string swapping. A naive implementation wowould look like this:

void naiveswap(string &a, string & b){ string temp = a; a=b; b=temp;}

This is expensive. copying a string entails the allocation of raw memory and copying the characters from the source to the target. in contrast, moving strings merely swaps two data members, without allocating memory, copying char arrays and deleting memory:

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 resources to empty empty.setsize(filled.size()); empty.setdata(filled.data());//filled becomes empty filled.setsize(sz); filled.setdata(p);}

If you're implementing a class that supports moving, you can declare a move constructor and a move assignment operator like this:

class Movable{Movable (Movable&&); //move constructorMovable&& operator=(Movable&&); //move assignment operator};

The C ++ 11 standard library uses move semantics extensively. Alibaba algorithms and containers are now move-optimized.

C ++ 11 standard library

C ++ underwent a major facelift in 2003 in the form of the library Technical Report 1 (tr1). tr1 sorted ded new container classes (unordered_set,unordered_map,unordered_multiset, Andunordered_multimap) And several new libraries for regular expressions, tuples, function object wrapper and more. with the approval of C ++ 11, tr1 is officially ininitialized into standard C ++ standard, along with new libraries that have been added since tr1. here are some of the C ++ 11 standard library features:

Threading Library

Unquestionably, the most important addition to C ++ 11 from a programmer's perspective is concurrency. c ++ 11 has a Thread class that represents an execution thread, promises and futures, which are objects that are used for synchronization in a concurrent Environment, The async () function template for launching concurrent tasks, and the thread_local storage type for declaring thread-unique data. for a quick tour of the C ++ 11 threading library, read Anthony Williams 'simpler multithreading in C ++ 0x.

New smart pointer classes

C ++ 98 defined only one smart pointer class,auto_ptr, Which is now deprecated. c ++ 11 primary des new smart pointer classes: shared_ptr and the recently-added unique_ptr. both are compatible with other standard library components, so you can safely store these smart pointers in standard containers and manipulate them with standard algorithms.

New Algorithms

The C ++ 11 standard library defines new algorithms that mimic the Set Theory Operationsall_of(),any_of()Andnone_of(). The following listing applies the Predicateispositive()To the range[first, first+n)And usesall_of(),any_of()Andnone_of()To examine the range's properties:

#include <algorithm>//C++11 code//are all of the elements positive?all_of(first, first+n, ispositive()); //false//is there at least one positive element?any_of(first, first+n, ispositive());//true// are none of the elements positive?none_of(first, first+n, ispositive()); //false

A new categorycopy_nAlgorithms is also available. Usingcopy_n(), Copying an array of 5 elements to another array is a cinch:

#includeint source[5]={0,12,34,50,80};int target[5];//copy 5 elements from source to targetcopy_n(source,5,target);

The Algorithmiota()Creates a range of sequentially increasing values, as if by assigning an initial value*first, Then incrementing that value using prefix ++. In the following listing,iota()Assigns the consecutive values {10, 11, 12, 13, 14} to the arrayarr, And {'A', 'B', 'C'} to the char arrayc.

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'}

C ++ 11 still lacks a few useful libraries such as an xml api, sockets, Gui, reflection-and yes, a proper automated garbage collector. however, it does offer plenty of new features that will make C ++ more secure, efficient (yes, even more efficient than it has been thus far! See Google's benchmark tests), and easier to learn and use.

If the changes in C ++ 11 seem overwhelming, don't be alarmed. take the time to digest these changes gradually. at the end of this process you will probably agree with stroustrup: C ++ 11DoesFeel like a new language-a much better one.

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.