C++11 new elements of modern C + + style--Introduction

Source: Internet
Author: User

The C++11 Standard introduces a number of useful new features, and this article pays particular attention to those features that are more like a new language than c++98, for the following reasons:

    • These features change the code style and idiom "1" that you use to write C + + programs, and often include the way you design C + + libraries. For example, you'll see more parameters and return value types as smart pointers (smart pointer), and you'll see functions returning large objects by value passing. You will find a new feature in most of the code examples. For example, almost every 5 lines of modern C + + code samples will be used to auto.
    • Other features of c++11 are also great. But familiarize yourself with the following, because the extensive use of these features makes the C++11 code as neat, secure, and efficient as any other modern mainstream language, while preserving the traditional performance advantages of C + +.

Tips:

    • As with Strunk & White "2", this article does a summary rather than a detailed rationale and pros and cons analysis. For detailed analysis, see other articles.
    • This article will be constantly updated, major changes and content additions please refer to the change history at the end of this document.

Moqtada

1. Programming Idiom: A programming idiom, a repeating expression in one or more programming languages, that represents a simple task or algorithm that is not built into a programming language, or that is used to represent an uncommon or atypical feature built into a programming language. Programming idioms can also be used in a broader context, such as referring to complex algorithms or design patterns .

2. Strunk & White: William Strunk Jr. and E. B. White published the "The Elements of Style", the Chinese version of the "Elements of Style," a book that describes the basic style of English writing to follow.


Auto

Use Autoas much as possible for the following two reasons: First, using auto avoids repeatedly declaring types that the compiler already knows.

12345 // C++98 map<int,string>::iterator i = m.begin();  // C++11 auto i = begin(m);

Second, using Auto when unknown type or type name is not easy to understand is more convenient, such as most lambda functions "3"-you can't even spell the name of the type easily.

12345 //c++98 binder2nd< greater< int > > x = bind2nd (greater< int > (), 42); &NBSP;   //c++11 auto x = [] ( int   i) { return   i >;};

It is important to note that using Auto does not change the meaning of the code. The code is still the static type "4", and the type of each expression is clear and unambiguous; c++11 just doesn't need us to repeat the type name. Some people may be afraid to use autohere at first, because it feels as if there is no (repeating) declaration that the type we need means that it might happen to get a different type. If you want to explicitly make a forced type conversion , there is no problem, declaring the target type is fine. In most cases, however, it is possible to use auto , and there is almost no mistake to get a different type of case, even if there is an error, C + + 's strong static type system will let you know the error by the compiler, Because you are trying to access a member function that does not have a variable or incorrectly invokes the function.

Moqtada

3. Lambda function (lambda functions): The programming language supports the lambda function/λ expression can make the code easier to understand, but also can make the code more concise, about the lambda function technical explanation can refer to, Wikipedia labmda calculus, also can from the. The evolution of delegate writing in net talk about (middle): lambda expression and its benefits blog is an intuitive explanation.

4. Dynamic type language (typing language) refers to the language in which type checking occurs during run time (Run-time). The static type language (static typing language) is the language in which type checking occurs during compilation (Compile-time).

Smart pointer: no delete

Always use standard smart pointers and non-possessive raw pointers (non-owning raw pointer). Never use possessive native pointers (owning raw pointer) and Delete operations unless you are in a rare situation where you are implementing your own underlying data structure (even at this point you need the class In a package that remains intact within the range). If you can only know that you are the only owner of another object, use unique_ptr to represent unique ownership. A "new T" expression immediately initializes another object that references it, usually a unique_ptr.

1234567891011121314151617181920 // C++11 Pimpl Idiom classwidget { widget(); ~widget(); private: classimpl; unique_ptr<impl> pimpl; };  // in .cpp file classimpl { ::: };  widget::widget() : pimpl( newimpl() ) { }  widget::~widget() = default;

Use shared_ptr to represent shared ownership. It is recommended to use make_shared to create shared objects efficiently.

1234567 // C++98 widget* pw = newwidget(); ::: delete pw;  // C++11 auto pw = make_shared<widget>();

Use weak_ptr to exit the loop and indicate an option (for example, implementing an object cache)

123456789101112 // C++11 classgadget;  classwidget { private: shared_ptr<gadget> g; // if shared ownership };  class gadget { private: weak_ptr<widget> w; };

If you know that another object exists longer and wants to track it, use a non-possessive (non-owning) primitive pointer.

1234567 // C++11 classnode { vector< unique_ptr<node> > children; node* parent; public: ::: };

Nullptr

Always use nullptr to represent a null pointer value, never use a number 0 or a NULL macro, because they can also represent an integer or pointer to create ambiguity.

12345 // C++98 int* p = 0;  // C++11 int* p = nullptr;

Range for

A range-based loop makes it convenient to access each of these elements sequentially.

123456789 // C++98 for( vector<double>::iterator i = v.begin(); i != v.end(); ++i ) { total += *i; }  // C++11 for( auto d : v ) { total += d; }

Non-member (nonmember) Begin and end

Always use non-member begin and end, because it is extensible and can be applied in all container types (container type), not just following the STL style provided . Begin () and . End () member functions, even arrays can be used.

If you are using a non-STL-style collection type, although you provided an iteration but did not provide the STL . Begin ( ) and . End (), You can usually write your own non-member begin and end for this type to overload. This way you can use the programming style of the STL container to traverse the type. The C++11 standard provides a sample array that is a type that provides both begin and endfor arrays.

12345678910 VECTOR< int > v; int  a[100]; &NBSP;  //c++98 Sort (V.begin (), V.end ()); sort (&a[0], &a[0] + sizeof (a)/ sizeof &NBSP;  //c++11 sort (Begin (V), End (v)); sort (Begin (a), End (a));

Lambda functions and algorithms

A lambda function is a factor that determines the universe, and it makes the code you write more elegant and faster. Lambda makes the availability of STL algorithms nearly 100 times times higher. The newly developed C + + libraries are all based on the premise that Lambda is available (for example, PPL) and some libraries even require you to write a lambda to invoke a library of functions (for example, C + + AMP)

Here's a quick example: find the first element inside v greater than x and less than y . In C++11, the simplest and cleanest code is to call a standard function.

12345678 // C++98: 直接编写一个循环 (使用std::find_if会非常困难) vector<int>::iterator i = v.begin(); // 因为我们需要在后边用到i for( ; i != v.end(); ++i ) { if( *i > x && *i < y ) break; }  // C++11: use std::find_if auto i = find_if( begin(v), end(v), [=](inti) { returni > x && i < y; } );

Want to write a loop or similar new feature in C + +? Don't worry; just write a template function (library algorithm) and use lambda almost as a language feature, while being more flexible. Because it's not a fixed language feature but a real library of functions.

1234 // C# lock( mut_x ) { ... use x ... }
1234567891011 // 不使用lambda的C++11:已经非常简洁并且更灵活(例如,可以使用超时以及其他选项) { lock_guard<mutex> hold( mut_x ); ... use x ... }  // 使用了lambda的C++11可以带一个辅助算法:在C++中使用C#的文法 // 算法:template<typename T, typename F> void lock( T& t, F f ) { lock_guard<T> hold(t); f(); } lock( mut_x, [&]{ ... use x ... });

Get familiar with Lambda. You will continue to use it, not just in C + +,--LAMBDA has been widely used in many mainstream programming languages. A good place to start, please refer to my speech in PDC2010, "The ubiquitous lambda"

Move/&&

Move is considered to be the best optimization for copy , although it also makes other things possible such as information being forwarded.

12345678910111213 // C++98:避免copy的替代方法 vector<int>* make_big_vector(); // 选择1: 返回指针: 没有拷贝,但不要忘记delete ::: vector<int>* result = make_big_vector(); voidmake_big_vector( vector<int>& out ); // 选择2: 通过引用传递: 没有拷贝,但是调用者需要传入一个有名对象 ::: vector<int> result; make_big_vector( result );  // C++11: move vector<int> make_big_vector(); // 通常对于”被调用者(callee)分配的空间“也适用 ::: vector<int> result = make_big_vector();

The move syntax changes the way we design the API. We can design more by value delivery. Enable the move syntax for your type, which is more efficient than copy .

More changes

There are more features of modern C + +. And I plan to write more essays in the future that will further c++11 new features and other features, and we'll know more and like it.

But for now, this is a new feature that must be known. These features make up the core of modern C + + style, making C + + code look and execute as they are designed, and you will see that these features appear in almost every modern C + + code you see or write. And they make modern C + + cleaner, safer and faster, so that C + + will continue to be our industry's reliance for several years to come.

C++11 new elements of modern C + + style--Introduction

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.