Archive
My C++11 “Move” Notes
Being a slow learner, BD00 finds it easier to learn a new topic by researching the writings from multiple sources of authority. BD00 then integrates his findings into his bug-riddled brain as “the truth as he sees it” (not the absolute truth – which is unknowable). The different viewpoints offered up by several experts on a subject tend to fill in holes of understanding that would otherwise go unaddressed. Thus, since BD00 wanted to learn more about how C++11′s new “move” and “rvalue reference” features work, he gathered several snippets on the subject and hoisted them here.
Why Move?
The motivation for adding “rvalue” references and “move” semantics to C++11 to complement its native “copy” semantics was to dramatically improve performance when large amounts of heap-based data need to be transferred from one class object to another AND it is known that preserving the “from” class object’s data is unnecessary (e.g. returning a non-static local object from a function). Rather than laboriously copying each of a million objects from one object to another, one can now simply “move” them.
Unlike its state after a “copy“, a moved-from object’s data is no longer present for further use downstream in the program. It’s like when I give you my phone. I don’t make a copy of it and hand it over to you. After I “move” it to you, I’m sh*t outta luck if I want to call my shrink – until I get a new phone.
Chapter 13 – C++ Primary, Fifth Edition, Lippman, Lajoie, Moo
Chapter 3 – The C++ Programming Language, 4th Edition, Bjarne Stroustrup
Chapter 3 – The C++ Standard Library, 2nd Edition, Nicolai M. Josuttis
Overview Of The New C++ (C++11), Scott Meyers
A Glimpse Into C++11PL4
At Microsoft’s Build 2012 conference, ISO C++ chairman Herb Sutter introduced the new isocpp.org web site. On the site, you can download a draft version of Chapter 2 from Bjarne Stroustrup‘s upcoming “The C++ Programming Language, 4th Edition“. As I read the chapter and took “the tour“, I noted the new C++11 features that Bjarne used in his graceful narrative. Here they are:
auto, intializer lists, range-for loops, constexpr, enum class, nullptr, static_assert.
Since I’m a big Stroustrup and C++ fan, I just wanted to pass along this tidbit of info to the C++ programmers that happen to stumble upon this blog.
Patience Grasshoppa, Patience
It won’t arrive for awhile, but it’s on its way: the C++11 rendition of Bjarne Stroustrup‘s “The C++ Programming Language“.
In case you didn’t already know, the C++11 editions of these tomes are already available for your consumption:
But of course, you did already did know this. There are gifted copies of each of these references on your and your colleague’s desks because your company cares about you, your productivity growth, and continuously enhancing the quality of its revenue-generating product portfolio. That’s why it obsesses over little, but simultaneously huge, things like this for you, its products, and its future well being. It’s a quiet, low-key, low-cost, win-win-win situation that makes you feel warm and fuzzy each day you walk in the door to joyfully add your contribution to the whole.
And puh-leeze, no comments from the hip and cool Ruby, Python, Java, Go, Scala, C#, etc, peanut galleries. On this bogus blawg, only pope BD00 is approved to promote or trash other programming languages, ideas, groups, concepts, institutions, traditions. Well, you get the idea.
Note: I created the above image at says-it.com. It’s a wonderful site, so hop on over there and give it a whirl.
Misapplication Of Partially Mastered Ideas
Because the time investment required to become proficient with a new, complex, and powerful technology tool can be quite large, the decision to design C++ as a superset of C was not only a boon to the language’s uptake, but a boon to commercial companies too – most of whom developed their product software in C at the time of C++’s introduction. Bjarne Stroustrup‘s decision killed those two birds with one stone because C++ allowed a gradual transition from the well known C procedural style of programming to three new, up-and-coming mainstream styles at the time: object-oriented, generic, and abstract data types. As Mr. Stroustrup says in D&E:
Companies simply can’t afford to have significant numbers of programmers unproductive while they are learning a new language. Nor can they afford projects that fail because programmers over enthusiastically misapply partially mastered new ideas.
That last sentence in Bjarne’s quote doesn’t just apply to programming languages, but to big and powerful libraries of functionality available for a language too. It’s one challenge to understand and master a language’s technical details and idioms, but another to learn network programming APIs (CORBA, DDS, JMS, etc), XML APIs, SQL APIs, GUI APIs, concurrency APIs, security APIs, etc. Thus, the investment dilemma continues:
I can’t afford to continuously train my programming workforce, but if I don’t, they’ll unwittingly implement features as mini booby traps in half-learned technologies that will cause my maintenance costs to skyrocket.
BD00 maintains that most companies aren’t even aware of this ongoing dilemma – which gets worse as the complexity and diversity of their product portfolio rises. Because of this innocent, but real, ignorance:
- they don’t design and implement continuous training plans for targeted technologies,
- they don’t actively control which technologies get introduced “through the back door” and get baked into their products’ infrastructure; receiving in return a cacophony of duplicated ways of implementing the same feature in different code bases.
- their software maintenance costs keep rising and they have no idea why; or they attribute the rise to insignificant causes and “fix” the wrong problems.
I hate when that happens. Don’t you?
The “Void Star” Crowd
During the “Ask Us Anything” panel discussion at the “Going Native 2012” conference, one of the questions asked was: how do you get the “void *” guys to move forward toward a more type-safe and abstract C++ style of programming?“.
By “void *“, the questioner meant programmers who still cling to writing code like this:
instead of this:
The panelists admitted that it was a big challenge, and they gave the following suggestions:
- Ask them what problems they’re having and then show them the solution by doing it for them in C++ style. (Stroustrup)
- Set a personal example of increased productivity. (Alexandrescu)
- Show them compiler generated assembly output comparing the “void *“ C-style code with a more expressive, less error-prone, more readable C++ equivalent. Odds are that the compiler-optimized C++ code will be much shorter than the hand-crafted C code. (STL)
Bjarne Stroustrup seemed especially frustrated at the pervasiveness of “void *” mindset. As a professor at Texas A&M, he said that as people come out of high school, most of them want to write games and they’ve convinced themselves and each other that, beyond a shadow of a doubt, “void *” is as fast as one can get. That’s exacerbated by the fact that many professors and “greybeards” still code in the type unsafe, barely readable, and error prone “void *” way.
I can sympathize with Bjarne and the panel. When I made the transition from C to C++, it took me what-seemed-like forever to “graduate” from arrays and naked pointers to containers and smart pointers and algorithms. Luckily, I did it in spite of myself. I can’t even remember the last time I used “void *” in any of the code I wrote.
Efficient Abstraction
In “The Design And Evolution Of C++“, Bjarne Stroustrup presents a tree-like picture on the history of programming languages and how they’ve influenced each other. For your studying pleasure, BD00 surgically extracted and augmented a slightly more C++ focused sub-tree. In other words, BD00 committed yet another act of plagiarism. I hope you like the result.
All through the 30+ years of C++’s evolution, Bjarne and the ISO C++ standards committee have maintained a fierce and agonizing determination to march to the tune of “efficient abstraction” over theoretical purity. Adding increasing support for abstraction without sacrificing much in efficiency is more of an art than science.
D&E is not just a history book. As the figure below shows, it won one of the “Software Development Productivity Awards” from Software Development magazine waaay back when. That’s because knowing “why” and “how” the (or any) language became the way it is gives a qualitative edge to those programmers over those who just know “what” the language is.
Sandwich Dilemma
In this dated, but still relevant paper, “Evolving a language in and for the real world“, Bjarne Stroustrup laments about one of the adoption problems that (still) faces C++:
Since the overarching theme of C++ is, and always has been, “efficient abstraction“, it’s not surprising that long time efficiency zealots and abstraction aficionados would be extremely skeptical of the value proposition served up by C++. I personally know this because I arrived at the C++ camp from the C world of “void *ptr” and bit twiddling. When I first started studying C++, its breadth of coverage, feature set, and sometimes funky syntax scared me into thinking that it wasn’t worth the investment of my time to “go there“.
I think it’s easier to get C programmers to make the transition to C++ than it is to get VM-based and interpreter-based programmers to make the transition. The education, more disciplined thinking style, and types of apps written (non-business, non-web) by “close to the metal” programmers maps into the C++ mindset more naturally.
What do you think? Is C++ the best of both worlds, or the worst of both worlds?
Broken Books
With the addition of features like auto, initializer lists, lambdas, and smart pointers, a lot of C++98 programming idioms and guidance have become obsolete now that C++11 is here. Thus, as Herb Sutter said at GoingNative 2012, a boatload of code examples in the best C++ books are now “broken“.
As a result, new and revamped versions of the books will take awhile to become available. Here’s Herb’s “estimated time of arrival” for several stalwart books:
In the meantime, you can feast your eyes on, and feed the left side of your brain with, these links:
- Bjarne Stroustrup’s C++11 FAQ page
- Wikipedia C++11
- Scott Meyers Overview Of C++11
- C++11 Features To GCC Compiler Map
- C++ Standards Committee Home Page
- GoingNative 2012
- C++11 Features in Visual C++ 11
- Clang Compiler C++11 Support
- Writing Modern C++ Code (Herb Sutter)
Do you know of any other good links to add to this post?
Vectors And Lists
In C++ programming, everybody knows that when an application requires lots of dynamic insertions into (and deletions from) an ordered sequence of elements, a linked list is much faster than a vector. Err, is it?
Behold the following performance graph that Bjarne Stroustrup presented during his keynote speech at “Going Native 2012“:
So, “WTF is up wit dat?”, you ask. Here’s what’s up wit dat:
The CPU load happens to be dominated by the time to traverse to the insertion/deletion point – and KNOT by the time to actually insert/delete the element. So, you still yell “WTF!“.
The answer to the seeming paradox is “compactness plus hardware cache“. If you’re not as stubborn and full of yourself as BD00, this answer “may” squelch the stale, flat-earth mindset that is still crying foul in your brain.
Since modern CPUs with big megabyte caches are faster at moving a contiguous block of memory than traversing a chain of links that reside outside of on-chip cache and in main memory, the results that Bjarne observed during his test should start to make sense, no?
To drive his point home, Mr. Stroustrup provided this vector-list example:
In addition to consuming more memory overhead, the likelihood that all the list’s memory “pieces” reside in on-chip cache is low compared to the contiguous memory required by the vector. Thus, each link jump requires access to slooow, off-chip, main memory.
The funny thing is that recently, and I mean really recently, I had to choose between a list and a vector in order to implement a time ordered list of up to 5000 objects. Out of curiosity, I wrote a quick and dirty little test program to help me decide which to use and I got the same result as Bjarne. Even with the result I measured, I still chose the list over the vector!
Of course, because of my entrenched belief that a list is better than a vector for insertion/deletion heavy situations, I rationalized my unassailable choice by assuming that I somehow screwed up the test program. And since I was pressed for time (so, what else is new?), I plowed ahead and coded up the list in my app. D’oh!
Update 4/21/13: Here’s a short video of Bjarne himself waxing eloquent on this unintuitive conclusion: “linked list avoidance“.






















