{"id":475,"date":"2017-06-29T07:54:53","date_gmt":"2017-06-29T07:54:53","guid":{"rendered":"http:\/\/imalogic.com\/blog\/?p=475"},"modified":"2017-06-29T07:59:15","modified_gmt":"2017-06-29T07:59:15","slug":"changes-in-c11","status":"publish","type":"post","link":"https:\/\/imalogic.com\/blog\/2017\/06\/29\/changes-in-c11\/","title":{"rendered":"Changes in C++11"},"content":{"rendered":"<body><p>Let\u2019s look at some of the prominent C++11 core-language features.<\/p>\n<h2>Lambda Expressions<\/h2>\n<p>A\u00a0lambda expression\u00a0lets 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:<\/p>\n<p>[capture](parameters)-&gt;return-type {body}<\/p>\n<p>The\u00a0<code><tt>[]<\/tt><\/code>\u00a0construct inside a function call\u2019s argument list indicates the beginning of a lambda expression. Let\u2019s see a lambda example.<\/p>\n<p>Suppose you want to count how many uppercase letters a string contains. Using\u00a0<code><tt>for_each()<\/tt><\/code>\u00a0to traverses a char array, the following lambda expression determines whether each letter is in uppercase. For every uppercase letter it finds, the lambda expression increments\u00a0<code><tt>Uppercase<\/tt><\/code>, a variable defined outside the lambda expression:<\/p>\n<pre><tt>int main()<\/tt>\r\n<tt>{<\/tt>\r\n   <tt>char s[]=\"Hello World!\";<\/tt>\r\n   <tt>int Uppercase = 0; \/\/modified by the lambda<\/tt>\r\n   <tt>for_each(s, s+sizeof(s), [&amp;Uppercase] (char c) {<\/tt>\r\n    <tt>if (isupper(c))<\/tt>\r\n     <tt>Uppercase++;<\/tt>\r\n    <tt>});<\/tt>\r\n <tt>cout&lt;&lt; Uppercase&lt;&lt;\" uppercase letters in: \"&lt;&lt; s&lt;&lt;endl;<\/tt>\r\n<tt>}<\/tt><\/pre>\n<p>It\u2019s as if you defined a function whose body is placed inside another function call. The ampersand in\u00a0<em>[&amp;Uppercase]<\/em>\u00a0means that the lambda body gets a reference to\u00a0<em>Uppercase<\/em>\u00a0so it can modify it. Without the ampersand,\u00a0<em>Uppercase<\/em>\u00a0would be passed by value. C++11 lambdas include constructs for member functions as well.<\/p>\n<h2>Automatic Type Deduction and\u00a0<code>decltype<\/code><\/h2>\n<p>In C++03, you must specify the type of an object when you declare it. Yet in many cases, an object\u2019s declaration includes an initializer. C++11 takes advantage of this, letting you\u00a0declare objects without specifying their types:<\/p>\n<pre><tt>auto x=0; \/\/x has type int because 0 is int\r\n<tt>auto c='a'; \/\/char\r\nauto d=0.5; \/\/double<\/tt>\r\n<tt>auto national_debt=14400000000000LL;\/\/long long<\/tt><\/tt><\/pre>\n<p>Automatic type deduction is chiefly useful when the type of the object is verbose or when it\u2019s automatically generated (in templates). Consider:<\/p>\n<pre><tt>void func(const vector&lt;int&gt; &amp;vi)<\/tt>\r\n<tt>{<\/tt>\r\n<tt>    vector&lt;int&gt;::const_iterator ci=vi.begin();<\/tt>\r\n<tt>}<\/tt><\/pre>\n<p>Instead, you can declare the iterator like this:<\/p>\n<pre><tt>auto ci=vi.begin();<\/tt><\/pre>\n<blockquote><p>The keyword\u00a0<code><tt>auto<\/tt><\/code>\u00a0isn\u2019t new; it actually dates back the pre-ANSI C era. However, C++11 has changed its meaning;\u00a0<code><tt>auto<\/tt><\/code>\u00a0no longer designates an object with automatic storage type. Rather, it declares an object whose type is deducible from its initializer. The old meaning of\u00a0<code><tt>auto<\/tt><\/code>\u00a0was removed from C++11 to avoid confusion.<\/p><\/blockquote>\n<p>C++11 offers a similar mechanism for capturing the type of an object or an expression. The new operator\u00a0<code><tt>decltype<\/tt><\/code>\u00a0takes an expression and \u201creturns\u201d its type:<\/p>\n<pre><tt>const vector&lt;int&gt; vi;\r\ntypedef decltype (vi.begin()) CIT;<\/tt>\r\n<tt>CIT another_const_iterator;<\/tt><\/pre>\n<h2>Uniform Initialization Syntax<\/h2>\n<p>C++ has at least four different initialization notations, some of which overlap.<\/p>\n<p>Parenthesized initialization looks like this:<\/p>\n<pre><tt>std::string s(\"hello\");<\/tt>\r\n<tt>int m=int(); \/\/default initialization<\/tt><\/pre>\n<p>You can also use the\u00a0<code><tt>=<\/tt><\/code>\u00a0notation for the same purpose in certain cases:<\/p>\n<pre><tt>std::string s=\"hello\";<\/tt>\r\n<tt>int x=5;<\/tt><\/pre>\n<p>For POD aggregates, you use braces:<\/p>\n<pre><tt>int arr[4]={0,1,2,3};<\/tt>\r\n<tt>struct tm today={0};<\/tt><\/pre>\n<p>Finally, constructors use member initializers:<\/p>\n<pre><tt>struct S {<\/tt>\r\n <tt>int x;<\/tt>\r\n <tt>S(): x(0) {} };<\/tt><\/pre>\n<p>This proliferation is a fertile source for confusion, not only among novices. Worse yet, in C++03 you can\u2019t initialize POD array members and POD arrays allocated using\u00a0<code><tt>new[]<\/tt><\/code>. C++11 cleans up this mess with a uniform brace notation:<\/p>\n<pre><tt>class C<\/tt>\r\n<tt>{<\/tt>\r\n<tt>int a;<\/tt>\r\n<tt>int b;<\/tt>\r\n<tt>public:<\/tt>\r\n <tt>C(int i, int j);<\/tt>\r\n<tt>};<\/tt>\r\n\r\n<tt>C c {0,0}; \/\/C++11 only. Equivalent to: C c(0,0);<\/tt>\r\n\r\n<tt>int* a = new int[3] { 1, 2, 0 }; \/C++11 only<\/tt>\r\n\r\n<tt>class X {<\/tt>\r\n  <tt>int a[4];<\/tt>\r\n<tt>public:<\/tt>\r\n  <tt>X() : a{1,2,3,4} {} \/\/C++11, member array initializer<\/tt>\r\n<tt>};<\/tt><\/pre>\n<p>With respect to containers, you can say goodbye to a long list of\u00a0<code><tt>push_back()<\/tt><\/code>calls. In C++11 you can initialize containers intuitively:<\/p>\n<pre><tt>\/\/ C++11 container initializer<\/tt>\r\n<tt>vector&lt;string&gt; vs={ \"first\", \"second\", \"third\"};<\/tt>\r\n<tt>map singers =<\/tt>\r\n  <tt>{ {\"Lady Gaga\", \"+1 (212) 555-7890\"},<\/tt>\r\n    <tt>{\"Beyonce Knowles\", \"+1 (212) 555-0987\"}};<\/tt><\/pre>\n<p>Similarly, C++11 supports in-class initialization of data members:<\/p>\n<pre><tt>class C<\/tt>\r\n<tt>{<\/tt>\r\n <tt>int a=7; \/\/C++11 only<\/tt>\r\n<tt>public:<\/tt>\r\n<tt> C();<\/tt>\r\n<tt>};<\/tt><\/pre>\n<h2>Deleted and Defaulted Functions<\/h2>\n<p>A function in the form:<\/p>\n<pre><tt>struct A<\/tt>\r\n<tt>{<\/tt>\r\n <tt>A()=default; \/\/C++11<\/tt>\r\n <tt>virtual ~A()=default; \/\/C++11<\/tt>\r\n<tt>};<\/tt><\/pre>\n<p>is called a\u00a0<em>defaulted function<\/em>. The\u00a0<code><tt>=default;<\/tt><\/code>\u00a0part 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.<\/p>\n<p>The opposite of a defaulted function is a\u00a0<em>deleted function<\/em>:<\/p>\n<pre><tt>int func()=delete;<\/tt><\/pre>\n<p>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\u00a0<code><tt>=delete<\/tt><\/code>:<\/p>\n<pre><tt>struct NoCopy<\/tt>\r\n<tt>{<\/tt>\r\n<tt> NoCopy &amp; operator =( const NoCopy &amp; ) = delete;<\/tt>\r\n<tt> NoCopy ( const NoCopy &amp; ) = delete;<\/tt>\r\n<tt>};<\/tt>\r\n<tt>NoCopy a;<\/tt>\r\n<tt>NoCopy b(a); \/\/compilation error, copy ctor is deleted<\/tt><\/pre>\n<h2>nullptr<\/h2>\n<p>At last, C++ has a keyword that designates a null pointer constant.\u00a0<code>nullptr<\/code>replaces the bug-prone\u00a0<code><tt>NULL<\/tt><\/code>\u00a0macro and the literal 0 that have been used as null pointer substitutes for many years.\u00a0<code><tt>nullptr<\/tt><\/code>\u00a0is strongly-typed:<\/p>\n<pre><tt>void f(int); \/\/#1<\/tt>\r\n<tt>void f(char *);\/\/#2<\/tt>\r\n<tt>\/\/C++03<\/tt>\r\n<tt>f(0); \/\/which f is called?<\/tt>\r\n<tt>\/\/C++11<\/tt>\r\n<tt>f(nullptr) \/\/unambiguous, calls #2<\/tt><\/pre>\n<p><code><tt>nullptr<\/tt><\/code>\u00a0is applicable to all pointer categories, including function pointers and pointers to members:<\/p>\n<pre><tt>const char *pc=str.c_str(); \/\/data pointers<\/tt>\r\n<tt>if (pc!=nullptr)<\/tt>\r\n  <tt>cout&lt;&lt;pc&lt;&lt;endl;<\/tt>\r\n<tt>int (A::*pmf)()=nullptr; \/\/pointer to member function<\/tt>\r\n<tt>void (*pmf)()=nullptr; \/\/pointer to function<\/tt><\/pre>\n<h2>Delegating Constructors<\/h2>\n<p>In C++11 a <strong>constructor<\/strong> may <strong>call another constructor<\/strong> of the<strong> same class<\/strong>:<\/p>\n<pre><tt>class M \/\/C++11 delegating constructors\r\n{<\/tt>\r\n <tt>int x, y;<\/tt>\r\n<tt> char *p;<\/tt>\r\n<tt>public:<\/tt>\r\n<tt> M(int v) : x(v), y(0), p(new char [MAX]) {} \/\/#1 target<\/tt>\r\n <tt>M(): M(0) {cout&lt;&lt;\"delegating ctor\"&lt;&lt;endl;} \/\/#2 delegating<\/tt>\r\n<tt>};<\/tt><\/pre>\n<p>Constructor #2, the delegating constructor, invokes the\u00a0<em>target constructor<\/em>\u00a0#1.<\/p>\n<h2>Rvalue References<\/h2>\n<p>Reference types in C++03 can only bind to\u00a0lvalues. C++11 introduces a new category of reference types called\u00a0<em>rvalue references<\/em>. Rvalue references can bind to rvalues, e.g.\u00a0temporary objects\u00a0and literals.<\/p>\n<p>The primary reason for adding rvalue references is\u00a0<em>move semantics<\/em>. Unlike traditional copying, moving means that a target object\u00a0<em>pilfers<\/em>\u00a0the resources of the source object, leaving the source in an \u201cempty\u201d 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 would look like this:<\/p>\n<pre><tt>void naiveswap(string &amp;a, string &amp; b)<\/tt>\r\n<tt>{<\/tt>\r\n <tt>string temp = a;<\/tt>\r\n<tt> a=b;<\/tt>\r\n<tt> b=temp;<\/tt>\r\n<tt>}<\/tt><\/pre>\n<p>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:<\/p>\n<pre><tt>void moveswapstr(string&amp; empty, string &amp; filled)<\/tt>\r\n<tt>{<\/tt>\r\n<tt>\/\/pseudo code, but you get the idea<\/tt>\r\n <tt>size_t sz=empty.size();<\/tt>\r\n <tt>const char *p= empty.data();<\/tt>\r\n<tt>\/\/move filled's resources to empty<\/tt>\r\n <tt>empty.setsize(filled.size());<\/tt>\r\n<tt> empty.setdata(filled.data());<\/tt>\r\n<tt>\/\/filled becomes empty<\/tt>\r\n <tt>filled.setsize(sz);<\/tt>\r\n <tt>filled.setdata(p);<\/tt>\r\n<tt>}<\/tt><\/pre>\n<p>If you\u2019re implementing a class that supports moving, you can declare a move constructor and a move assignment operator like this:<\/p>\n<pre><tt>class Movable<\/tt>\r\n<tt>{<\/tt>\r\n<tt>Movable (Movable&amp;&amp;); \/\/move constructor<\/tt>\r\n<tt>Movable&amp;&amp; operator=(Movable&amp;&amp;); \/\/move assignment operator<\/tt>\r\n<tt>};<\/tt><\/pre>\n<p>The C++11 Standard Library uses move semantics extensively. Many algorithms and containers are now move-optimized.<\/p>\n<h2>C++11 Standard Library<\/h2>\n<p>C++ underwent a major facelift in 2003 in the form of the\u00a0Library Technical Report 1(TR1). TR1 included new container classes (<code><tt>unordered_set<\/tt><\/code>,\u00a0<code><tt>unordered_map<\/tt><\/code>,\u00a0<code><tt>unordered_multiset<\/tt><\/code>, and\u00a0<code><tt>unordered_multimap<\/tt><\/code>) and several new libraries for regular expressions, tuples, function object wrapper and more. With the approval of C++11, TR1 is officially incorporated into standard C++ standard, along with new libraries that have been added since TR1. Here are some of the C++11 Standard Library features:<\/p>\n<h2>Threading Library<\/h2>\n<p>Unquestionably, the most important addition to C++11 from a programmer\u2019s perspective is concurrency. C++11 has a thread class that represents an execution thread,\u00a0promises and futures, which are objects that are used for synchronization in a concurrent environment, the\u00a0async()\u00a0function template for launching concurrent tasks, and the\u00a0thread_local\u00a0storage type for declaring thread-unique data. For a quick tour of the C++11 threading library, read Anthony Williams\u2019\u00a0<a href=\"http:\/\/www.devx.com\/SpecialReports\/Article\/38883\">Simpler Multithreading in C++0x<\/a>.<\/p>\n<h2>New Smart Pointer Classes<\/h2>\n<p>C++98 defined only one smart pointer class,\u00a0<code><tt>auto_ptr<\/tt><\/code>, which is now deprecated. C++11 includes new smart pointer classes:\u00a0<a href=\"http:\/\/www.informit.com\/guides\/content.aspx?g=cplusplus&amp;seqNum=239\">shared_ptr<\/a>\u00a0and the recently-added\u00a0<a href=\"http:\/\/www.informit.com\/guides\/content.aspx?g=cplusplus&amp;seqNum=400\">unique_ptr<\/a>. 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.<\/p>\n<h2>New C++ Algorithms<\/h2>\n<p>The C++11 Standard Library defines new algorithms that mimic the set theory operations\u00a0<code><tt>all_of()<\/tt><\/code>,\u00a0<code><tt>any_of()<\/tt><\/code>\u00a0and\u00a0<code><tt>none_of()<\/tt><\/code>. The following listing applies the predicate\u00a0<code><tt>ispositive()<\/tt><\/code>\u00a0to the range\u00a0<code><tt>[first, first+n)<\/tt><\/code>\u00a0and uses\u00a0<code><tt>all_of()<\/tt><\/code>,\u00a0<code><tt>any_of()<\/tt><\/code>\u00a0and\u00a0<code><tt>none_of()<\/tt><\/code>\u00a0to examine the range\u2019s properties:<\/p>\n<pre><tt>#include &lt;algorithm&gt;<\/tt>\r\n<tt>\/\/C++11 code<\/tt>\r\n<tt>\/\/are all of the elements positive?<\/tt>\r\n<tt>all_of(first, first+n, ispositive()); \/\/false<\/tt>\r\n<tt>\/\/is there at least one positive element?<\/tt>\r\n<tt>any_of(first, first+n, ispositive());\/\/true<\/tt>\r\n<tt>\/\/ are none of the elements positive?<\/tt>\r\n<tt>none_of(first, first+n, ispositive()); \/\/false<\/tt><\/pre>\n<p>A new category of\u00a0<code><tt>copy_n<\/tt><\/code>\u00a0algorithms is also available. Using\u00a0<code><tt>copy_n()<\/tt><\/code>, copying an array of 5 elements to another array is a cinch:<\/p>\n<pre><tt>#include<\/tt>\r\n<tt>int source[5]={0,12,34,50,80};<\/tt>\r\n<tt>int target[5];<\/tt>\r\n<tt>\/\/copy 5 elements from source to target<\/tt>\r\n<tt>copy_n(source,5,target);<\/tt><\/pre>\n<p>The algorithm\u00a0<code><tt>iota()<\/tt><\/code>\u00a0creates a range of sequentially increasing values, as if by assigning an initial value to\u00a0<code><tt>*first<\/tt><\/code>, then incrementing that value using prefix ++. In the following listing,\u00a0<code><tt>iota()<\/tt><\/code>\u00a0assigns the consecutive values {10,11,12,13,14} to the array\u00a0<code><tt>arr<\/tt><\/code>, and {\u2018a\u2019, \u2018b\u2019, \u2018c\u2019} to the char array\u00a0<code><tt>c<\/tt><\/code>.<\/p>\n<pre><tt>include &lt;numeric&gt;<\/tt>\r\n<tt>int a[5]={0};<\/tt>\r\n<tt>char c[3]={0};<\/tt>\r\n<tt>iota(a, a+5, 10); \/\/changes a to {10,11,12,13,14}<\/tt>\r\n<tt>iota(c, c+3, 'a'); \/\/{'a','b','c'}<\/tt><\/pre>\n<p>C++11 still lacks a few useful libraries such as an XML API, sockets, GUI, reflection \u2014 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\u2019s\u00a0<a href=\"http:\/\/www.itproportal.com\/2011\/06\/07\/googles-rates-c-most-complex-highest-performing-language\/\">benchmark tests<\/a>), and easier to learn and use.<\/p>\n<p>If the changes in C++11 seem overwhelming, don\u2019t be alarmed. Take the time to digest these changes gradually. At the end of this process you will probably agree with Stroustrup: C++11\u00a0<em>does<\/em>\u00a0feel like a new language \u2014 a much better one.<\/p>\n<\/body>","protected":false},"excerpt":{"rendered":"<p>Let\u2019s look at some of the prominent C++11 core-language features. Lambda Expressions A\u00a0lambda expression\u00a0lets you define functions locally, at the<\/p>\n","protected":false},"author":1,"featured_media":476,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[7],"tags":[],"class_list":["post-475","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-coding"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/imalogic.com\/blog\/wp-content\/uploads\/2017\/06\/c-small_.png?fit=256%2C256&ssl=1","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p8J21V-7F","jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/posts\/475","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/comments?post=475"}],"version-history":[{"count":1,"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/posts\/475\/revisions"}],"predecessor-version":[{"id":477,"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/posts\/475\/revisions\/477"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/media\/476"}],"wp:attachment":[{"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/media?parent=475"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/categories?post=475"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/tags?post=475"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}