New features of C + + 11--"in-depth understanding of C + + 11:c++11 new features analysis and application" reading notes

Source: Internet
Author: User
Tags aliases function definition throw exception

Because of accidental opportunities, in the library to see the "in-depth understanding of C + + 11:c++11 new features and Applications" this book, roughly swept down, benefited, on the decisive loan, for some of the content of the detailed reading and personally programmed to test the relevant code, there is a collation of the basis for writing this reading notes. C + + as the first step into the programming language, has been full of feelings, and c++11 as a new standard although launched for some time, but because the total reason until now to begin to really understand, but a sentence echoed in the brain: when you think it is too late, exactly the earliest time! From c++98 to C++11, c+ +11 Standard experienced 10几 years of precipitation, with a new attitude to meet new challenges, long story short, go to the point, come together to understand it. (note: All code in this note is edited under Code::Blocks, compiled using gcc-4.9.3-std=c++11 mode)

New basic features of c++11

1.1 macros for compatibility with the C99 feature , you can check the compilation system's support for standard C libraries, but the test section shows undefined.

cout<<"Standard Clib:"<< __stdc_hosted__<<endl;//Standard Clib:1 (specifies whether the compiler target system contains the complete C library)cout<<"Standard C:"<<__STDC__<<endl;//__stdc__:1 (Specifies whether the compiler target system is consistent with the C standard)//cout<< "C standard Version:" <<__STDC_VERSION__<<endl;//TestGCC is not defined (supports version of standard C library)//cout<< "ISO/IEC:" <<__STDC_ISO_10646__<<endl; //TestGCC is not defined

1.2 __func__ the macro used to get the current function name string

Const Char * Stanard_macros (void) {    /       /...    return // return value: Stanard_macros   }    

The 1.3 _pragma preprocessing operator is the same as #pragma function, but because it supports passing strings, you can replace them with macro commands, such as for a single inclusion of a frequently used header file.

// header files prevent duplicates from being included #pragma once; _pragma ("once");     #define PRAGMA (x) _pragma (#x)    // Macro command can be used to implement the substitution string PRAGMA (once);

1.4 __va_args__ the macro definition of the variable length parameter refers to the last parameter of the parameter list in the macro definition is ..., and the implementation part can be replaced with __va_args__

//__file__ Current file path//__line__ The current line of text#defineLOG (...) { \fprintf (stderr,"%s:line%d:\t", __file__, __line__);//output wrong file and line number addressfprintf (stderr, __va_args__);//output the wrong datafprintf (stderr,"\ n"); \} LOG ("%s","NO err!");//Xxxx:xxxx:NO err!

1.5 new integer long long/unsignedlong long (not less than 64 bits in length)

    Long Long intLli =-90000000000LL; unsignedLong Long intUlli =9000000000000ULL; cout<<"llong_min:"<<LLONG_MIN<<endl;//llong_min: -9223372036854775808cout<<"Llong_max:"<<LLONG_MAX<<endl;//llong_max:9223372036854775807cout<<"Ullong_max:"<<ULLONG_MAX<<endl;//ullong_max:18446744073709551615

 1.6 Assertions help developers quickly locate bugs that violate program prerequisites, but assertions are only executed when the program is run, which in some cases is unacceptable, especially for errors that occur when the template is instantiated, should be determined at the compiler. The Static_assert assertion was introduced to solve the problem in c++11, which supports two parameter inputs, one that returns a bool type, and the other is a warning message.

Static_assert (sizeof(b) = =sizeof"Theparameters of bit_copy must has same width " // static assertion, compiler OK, return FALSE to trigger alarm message

The 1.7 noexcept modifier and the noexcept operator are provided for use by the library author, which indicates that if an exception occurs and does not throw, the compiler calls the Std::terminate () function directly to terminate the program, thereby preventing the propagation and spread of the exception. also: The C++11 destructor is noexcept (true) by default, and if you want to throw an exception, you need to declare noexcept (false) (from the book, but the self-test GCC does not have an exception thrown by the destructor).

Const Char * Stanard_macros (void) noexcept // equals noexcept (True), does not throw exception const Char * Stanard_macros (void) noexcept (true//noexcept can be an expression of type bool, If False, the exception is thrown normally, and true does not throw an exception

Fast initialization of class 1.8 member variables and new list initialization , in c++11, in addition to static variables, allows for in-place initialization of other variables with an equal sign or {}.

classmem{ Public: Mem (inti): M (i) {}; ~Mem () {}; Const Char*showmem (void) {std::cout<<"Mem:"<<m<<" "; return__func__; };Private:    intm{0};};//Fast Initialization//initialization list is better than in-place initialization of the listclassinit{ Public: Init (): A (0){}; Init (intD): Val ('G'), A (d) {};//Initialize the list after the actual effect, the effect is better than the list of initialization//~init () {throw 1;};~Init () {}; Const Char* Showpara (std::stringstr); intA;Private:    Charval{'g'};//quick initialization of member variablesMem mem{1}; STD::stringname{"Init"};};//quick initialization of member variables for C + +Init init1{5};//Unified list Initialization for C++11Init Init2;init1.showpara ("init1:");//init1:5 init1:g name:init mem:1 mem:showmemInit2.showpara ("Init2:");//init2:0 init2:g name:init mem:1 mem:showmem

1.9 Non-static members of sizeof, sizeof as an operator, are often used when working with arrays, classes, and objects, but in previous c++98, it is not possible to compile directly for non-static members and to borrow a pair of image instances.

    cout<<""<<sizeof(((Init *)0)->a) <<endl;    // c++98 When borrowing instance objects for non-static member lengths    cout<<""<<sizeof(init::a) <<endl;           // c++11 Support Direct Access

1.10 Extended friend usage, friend when a special keyword in C + +, on the one hand it allows programmers to save a lot of code, on the other hand, also destroys the package in OOP, in the c++11 to make improvements to ensure better use.

class ploy;typedef Ploy P; // Friend supports aliases, no class, and template declaration friend int>class  people{    friend T;}; People<P> PP;   // Type P (alias of Ploy) declared as friend of PP people<int// for the int type parameter template, the friend declaration is ignored

1.11 Final and override controls, the corresponding derived class that final is used to restrict the base class virtual function cannot override this virtual function, thus avoiding some interfaces being overwritten by overrides; Override specifies that the function must overload the virtual function of the base class, otherwise the compilation fails, which avoids errors such as some input names or prototype mismatches.

classmathobject{ Public:    Virtual DoubleArith () =0; Virtual voidPrint () =0;};classPrintable: Publicmathobject{ Public:    DoubleArith () =0;//pure virtual functions are allowed to be only 0    voidPrint () final{std::cout<<"Output is:"<< Arith () <<Std::endl; }};classADD2: Publicprintable{ Public: Add2 (DoubleADoubleb): X (a), Y (b) {}DoubleArith ()Override{//override specifies that the function is overloaded and checks for certain overloaded function checks, avoiding input errors        returnx+y; }//void Print () {}//compile error because parent class declares final, subclass does not allow overloadingPrivate:    Doublex, y;}

1.12 Default Template parameters , like templates and functions in c++11, support default parameters.

//class template c++98 is allowed, but is defined as requiredTemplate<typename T1, TypeName T2 =int>classdefclass1{};//allow, specify default template parameters for class templates//template<typename T1 = int, typename t2> class DefClass2; //do not compile, you must follow the principle of right-hand when specifying default values for multiple default template parameters//function Template c++11 addTemplate<typename T1, TypeName T2 =int>voidDefFunc1 (T1 A, T2 b); template<typename T1 =int, TypeName T2>voidDEFFUNC2 (T1 A, T2 b);//Allow

1.13 External Templates

The external template implementation relies on the existing features of c++98 and displays instantiation. This makes it possible to implement an instance once and use it multiple times.

Template <typename t>void Fun (T) {}    // templates function definition void fun<int > (int);           // Template Instantiation Declaration extern void fun<int> (int);    // Template External Declarations

1.14 Local or anonymous types make template arguments

C++11 supports anonymous or local types as the template's arguments, providing more ways to use them.

//2.13 Local and anonymous types as function template argumentsTemplate<typename t>classx{};template<typename t>voidTempfunc (T t) {};struct{inti;} B;typedefstruct{inti;} B;structc{} C; X<B> X1;//an anonymous struct is an argument, but only aliases are supported, and anonymous structs are not supported directly as argumentsX<c> x2;//local variables as argumentsTempfunc (b);//Anonymous type variable, C++11 allowsTempfunc (c);//local type variable, C++11 allows

Up to now, the more important parts of C++11 's new basic features are almost over, and from these changes it can be seen that c++11 is progressing in a more convenient and powerful direction, and these changes are just bucket, such as new lambda expressions, new implementations of class constructors, More normal Sfinae, these are worth reading, but it's a bit late today, I will end the Test side, I would like to thank the C++11 Committee, but also thank the author of the detailed elaboration, enjoy endless!

New features of C + + 11--"in-depth understanding of C + + 11:c++11 new features analysis and application" reading notes

Large-Scale Price Reduction
  • 59% Max. and 23% Avg.
  • Price Reduction for Core Products
  • Price Reduction in Multiple Regions
undefined. /
Connect with us on Discord
  • Secure, anonymous group chat without disturbance
  • Stay updated on campaigns, new products, and more
  • Support for all your questions
undefined. /
Free Tier
  • Start free from ECS to Big Data
  • Get Started in 3 Simple Steps
  • Try ECS t5 1C1G
undefined. /

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.