A little summary of using C++11

Source: Internet
Author: User

C++11 is not fresh technology, but for me, the work is not enough (the former club long-time use of gcc3.4.5, although last year rose 4.8.2, but the old module maintenance is still 3.4.5 majority; the new owner uses 4.4.6 and cannot fully support C + + 11, and there is an internal base library has already supported the C++11 STL part of the function), coupled with their own practice also write less, understand only a few simple fur,here is a summary of the C++11 study, hoping for others and the future I have a bit of technical knowledge index help. First of all, the wiki is the most comprehensive: https://en.wikipedia.org/wiki/C%2B%2B11, which is the complete new C + + functionality, the personal use of the compiler may not be fully supported, you can see this compiler + version of the C++1X support: http:/     /en.cppreference.com/w/cpp/compiler_support. Then, to see the English is not fast enough to find a more comprehensive Chinese summary (not all, or to see the wiki): Http://www.cnblogs.com/pzhfei/archive/2013/03/02/CPP_new_feature.html.

Introduction of new features

C++11 was previously known as c++0x because it was originally planned to be released in 2010, so some compilers used C++11 's compilation parameters:-std=c++0x, followed by:-std=c++11. The core of c++11 design is: Change the language less, change the base library more. The changes involve this: support for multithreaded programming (adding the thread library), enhanced generic programming (incremental hash container, tuple of any number of elements, bind function, lambda function), unified initialization (calling constructors in curly braces), performance (rvalue reference and move), Other STL libraries (regular expressions, atomic operations Libraries), plus some syntactic sugar support, such as: default, delete definition (you can delete the public function of the base class in the derived class), the definition of the bare string, the class non-static member variable directly assigned value, NULLPTR, Support for two consecutive right angle brackets, back return type, range-based for loop, constructor can call another constructor, override keyword for discovering virtual function overwrite error, string literal ...

Second, some commonly used new features \ Library

Pick a few common records as follows

1. Unified initialization

Before, I wanted to initialize a container with a map object, which would look like this:
STD::VECTOR<STD::MAP<STD::string, std::string> > a;std::map<std::  String, std::string> tmp;tmp.insert (Std::make_pair ("1""  2")); A.push_back (TMP) ;
Now, I can use curly braces directly:
STD::VECTOR<STD::MAP<STD::string, std::string"1"" 2 " } } }
Note: Partial unified initialization is not supported until gcc4.7.

2. function bindings and Lambda

function bindings are supported by the underlying library, converting a function to an object, using a lot of asynchronous programming (the callback function binds to an object, and then the object is handed to the notifier who completes the asynchronous work, which triggers the asynchronous callback call). Lambda syntax, it can be used with the algorithm of the standard library, or with BIND in asynchronous programming. Eg1:bind
class work {public:  void  do_work () {    "does work" << Std::endl;  }}; int Main () {work work    ;     = Std::bind (&work::d o_work, & Work);    Bar ();}
EG2: Clears the ' a ' character in the string:
std::string"abcdefgdaaa"; Tmp.erase (std::remove_if (Tmp.begin (), Tmp.end ( ), [] (char  x) {        return'a';     << tmp << Std::endl;
Lambda Syntax:[Capture] (parameters)->return-type->{body}[capture] (parameters) {body}[]//no variables defined. Using undefined variables can cause errors. [x, &y]//x is passed in as a value (default), and Y is passed in as a reference. [&]//Any external variables used are implicitly used in a quoted manner. [=]//Any external variables used are implicitly used in a value-based manner. [&, x]//x is used in a value-based manner. The remaining variables are used in a reference manner. [=, &z]//z is used in a quoted manner. The remaining variables are used in a value-transfer manner.Note: Lambda requires gcc4.5 before support

3. Set default values directly to class member variables

Non-static data member Initializerseg:
class a {public:    A () {}    explicit A (int  new_value): Value (new_ Value) {}    intget() {        return  value;    } Private :     int 5 // Direct Write default value } is supported;
Note: At least gcc4.7 required

4. New tuple type

When a tuple type transmits data consisting of multiple types, it can omit the definition of a struct and can have as many members as possible. eg
STD::TUPLE&LT;STD::string, std::string, std::string,int,int> record = Std::make_tuple ("a","b","C", -, $); Std::cout<< std::Get<0> (record) <<Std::endl;std::cout<< std::Get<4> (record) << Std::endl;
gcc4.4 support for the tuple is not complete (do not use the const character assigned value to string), need to gcc4.7 above to perfect.

5. Added hash table

Std::unordered_setstd::unordered_multisetstd::unordered_mapstd::unordered_multimap lookup performance is faster than set, map.

6. New Multithreading Support

STD::THREADSTD::ASYNCSTD::p Romise,std::future, to specifically explain the concept of promise, the future: "The main thread to create a promise, will be associated with the promise to the new thread , the new thread waits for the data to be fetched from promise, and the main thread passes promise to the desired setting value, and new threads receive notifications to continue down. "This shows that Promise/future is used for asynchronous programming when synchronization between threads is somewhat like an event notification under multithreaded programming. eg
#include <iostream>#include<functional>#include<thread>#include<future>voidShow (std::future<int>&fut) {Std::cout<<"Work Thread:"<< std::this_thread::get_id () <<Std::endl; intx = Fut.Get();//waiting to get resultsStd::cout << x <<Std::endl;}intMain () {std::cout<<"Main thread:"<< std::this_thread::get_id () <<Std::endl; std::p romise<int>promise; Std::future<int> Future =promise.get_future (); Std::thread Work_thread (Show, std::ref(future)); Std::this_thread::sleep_for (Std::chrono::seconds (3)); Promise.set_value (Ten);    Work_thread.join (); return 0;}
Note: promise/future requires at least gcc4.7 supportExtension Description: As can be seen from the above example, the standard library's promise/future does not support setting the callback function, it needs to wait for itself through the Get function, which is the asynchronous caller (main thread) actively waiting for notification, unlike JS can be called by the. Then function to set the callback notification function, the caller can be passive.Therefore, it is not possible to do a thorough asynchronous programming at this moment (a callback continues following the callback). But the. Then function is already in the planning, see: http://en.cppreference.com/w/cpp/experimental/future/thenhttp://stackoverflow.com/questions/35074578/ Understanding-continuations-with-stdfuturethen "with" and instead of waiting for the result, a continuation is "attached "To the asynchronous operation, which was invoked when the result was ready.""Does this, and when it was done, then does this , and when it was done, then does this ..."The advantage of having then function is that our code can be completely asynchronous, in the example above, I just tell the future callback function is XX, the main thread will not have to wait, it can do something else, when the work is done, the worker thread actively to trigger the call of the callback function xx. In addition, boost already has the then function,
#include <iostream>#include<string>#defineBoost_thread_provides_future#defineBoost_thread_provides_future_continuation#include<boost/thread/future.hpp>using namespaceboost;intMain () { future<int> f1 = Async ([] () {return 123; }); Future&LT;STD::string> F2 = F1.then ([] (future<int>f) {std::cout<< F.Get() << Std::endl;//Here . Get () won ' t block        returnSTD::string("Sgfsdfs"); });}
Reference: Http://stackoverflow.com/questions/22597948/using-boostfuture-with-then-continuations Some companies use boost, or build a base library from the implementation of Future.then () in boost, and you can do it in code: do this, and when it's done, then do the, and when it's is doing, then do th Is ....

7. Other

(1) You can define a string that does not need to be escaped, such as: std::string B = R "x (C:\ABC)" yy L) x ", where X (is an identifier, x can be any, maximum of 16 characters.) Note: Raw string literals requires at least gcc4.4 reference: Http://en.cppreference.com/w/cpp/language/string_ Literal (2) Regular expression library (3) constructor Delegate (4) Std::shared_ptr smart pointer (5) Railing-return-type back return type This article is located in: http://www.cnblogs.com/cswuyg/ P/6220671.html Study Reference: Https://en.wikipedia.org/wiki/C%2B%2B11http://en.cppreference.com/w/cpp/compiler_ supporthttp://www.cnblogs.com/pzhfei/archive/2013/03/02/cpp_new_feature.htmlhttp://www.cnblogs.com/l00l/ Archive/2012/02/04/2338038.html

A little summary of using C++11

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.