GotW #101: Compilation Firewalls, Part 2 (Difficulty: 8/10)

GotW #100 demonstrated the best way to express the Pimpl idiom using only standard C++11 features:

// in header file
class widget {
public:
    widget();
    ~widget();
private:
    class impl;
    unique_ptr<impl> pimpl;
};

// in implementation file
class widget::impl {
    // :::
};

widget::widget() : pimpl{ new impl{ /*...*/ } } { }
widget::~widget() { }                   // or =default

image

Guru Question

Is it possible to make the widget code easier to write by wrapping the Pimpl pattern in some sort of library helper? If so, how?

Try to make the widget code as convenient and concise as possible to write, with any compiler-generated semantics either correct by default or producing compile-time errors if the widget author forgets to write them.

 

[Update: Removed move operations from the basic pattern. Since not all Pimpl’d types need to be move-aware, it’s not really part of the core pattern.]

GotW #100: Compilation Firewalls

image

JG Questions

1. What is the Pimpl Idiom, and why is it useful?

Guru Questions

2. What is the best way to express the basic Pimpl Idiom in C++11?

3. What parts of the class should go into the impl object? Some potential options include:

  • put all private data (but not functions) into impl;
  • put all private members into impl;
  • put all private and protected members into impl;
  • put all private nonvirtual members into impl;
  • put everything into impl, and write the public class itself as only the public interface, each implemented as a simple forwarding function (a handle/body variant).

What are the advantages/drawbacks of each? How would you choose among them?

4. Does the impl require a back pointer to the public object? If yes, what is the best way to provide it? If not, why not?

A Passing of Giants

image
I don’t normally blog poetry, but the passing of our giants this past month has put me in such a mood.

.

What is built becomes our future
Hand-constructed, stone by stone
Quarried by our elders’ labors
Fashioned with their strength and bone
Dare to dream, and dare to conquer
Fears by building castles grand
But ne’er forget, and e’er remember
To take a new step we must stand
On the shoulders of our giants
Who, seeing off into the morrow,
Made the dreams of past turn truth —
How their passing is our sorrow.

Scott Meyers’ C++11 Materials: The Best Available Overview of C++11

Scott Meyers Presentation Materials: Overview of the New C++ (C++11)

 

People keep asking me where to find good information on C++11. Until now I’ve had to point them to blogs, and say that we’re all working on revising our books but it’ll take a while. It’s been an unsatisfying answer.

Finally I have a C++11 “book” I can direct people to: Today Scott Meyers announced that his fully-annotated C++11 training materials are now up-to-date with the final published standard.

This is the best overview of C++11 available today, and it’s good:

Presentation Materials: Overview of the New C++ (C++11)
by Scott Meyers

PDF $29.95

The PDF you’ll get is an exact snapshot of Scott’s full-color training materials on the day he generates the PDF. You’ll get not only the slides Scott shows in class, you’ll also get the accompanying notes—the very ones Scott uses. To see exactly what you’ll get you can view a free sample.

Specification of the new version of C++ (“C++11”) is finally complete, and many compilers (e.g., Visual C++ and Gnu C++) already offer many features from the revised language. And such features! auto-declared variables reduce typing drudgery and syntactic noise; Unicode and threading support address important functionality gaps; and rvalue references and variadic templates facilitate the creation of more efficient, more flexible libraries. The standard library gains resource-managing smart pointers, new containers, additional algorithms, support for regular expressions, and more. Altogether, C++11 offers much more than “old” C++. This intensively technical seminar introduces the most important new features in C++11 and explains how to get the most out of them.

I like Scott’s terms: Free updates for life, including major revisions, so it’ll never be out of date. DRM-free, so that you can copy, annotate, and print as you like.

If you want to know about C++11, invest the $30. You won’t regret it.

Disclaimer: I have no financial interest in recommending Scott’s materials. I just think they’re excellent and everyone should know about them.

Elements of Modern C++ Style

image

As I’m getting ready to resume writing a few new (or updated) Guru of the Week Items for the C++11 era, I’ve been looking through the wonderful features of C++11 and analyzing just which ones will affect the baseline style of how I write modern C++ code, both for myself and for publication.

I’ve gathered the results in a short page. Here’s the intro:

Elements of Modern C++ Style

“C++11 feels like a new language.” – Bjarne Stroustrup

The C++11 standard offers many useful new features. This page focuses specifically and only on those features that make C++11 really feel like a new language compared to C++98, because:

  • They change the styles and idioms you’ll use when writing C++ code, often including the way you’ll design C++ libraries. For example, you’ll see more smart pointers, and functions that return big objects by value.
  • They will be used so pervasively that you’ll probably see them in most code examples. For example, virtually every five-line modern C++ code example will say “auto” somewhere.

Use the other great C++11 features too. But get used to these ones first, because these are the pervasive ones that show why C++11 code is clean, safe, and fast – just as clean and safe as code written in any other modern mainstream language, and with C++’s traditional to-the-metal performance as strong as ever.

Like Strunk & White, this page is deliberately focused on brief summary guidance. It is not intended to provide exhaustive rationale and pro/con analysis; that will go into other articles.

I hope you find it useful.

Apologies in advance if some of the code snippets are odd or missing template argument lists. Let me know and I’ll fix any I missed. I think I restored them all (again), but am still fighting my tools, which keep sporadically eating angle-bracket lists. Someday someone will integrate good code authoring in a good editor for a good blogging platform; today’s tools are at best “adequate.”

Garbage Collection Synopsis, and C++

Insert your favorite "stop the world" joke here.

In response to my note about John McCarthy’s inventing automatic (non ref-counted) garbage collection, rosen4obg asked:

OK, GC was invented half a century ago. When it is going to land in the C++ world?

Here’s a short but detailed answer, which links to illuminating reading and videos.

The Three Kinds of GC

The three major families of garbage collection are:

  1. Reference counting.
  2. Mark-sweep (aka non-moving) collectors, where objects are collected but live objects don’t move. This is what McCarthy first invented.
  3. Mark-compact (aka moving) collectors, where live objects are moved together to make allocated memory more compact. Note that doing this involves updating pointers’ values on the fly. This category includes semispace collectors as well as the more efficient modern ones like the .NET CLR’s that don’t use up half your memory or address space.

When I say “automatic GC” I mean #2 or #3.

GC and C++

C++ has always supported #1 well via reference counted smart pointers. Those are now standard in C++11 in the form of unique_ptr, shared_ptr, weak_ptr. C++98 had auto_ptr, but it was never great and has been deprecated.

C++ has long supported #2, but less formally because the products were nonstandard, conservative, and not as portable. The major prior art is the Boehm (later Great Circle and Symantec) mark-sweep garbage collector. The new C++11 standard has just added a minimal GC ABI to more formally bless such non-moving collectors; see Stroustrup’s GC FAQ for more.

C++ cannot support #3 without at least a new pointer type, because C/C++ pointer values are required to be stable (not change their values), so that you can cast them to an int and back, or write them to a file and back; this is why we created the ^ pointer type for C++/CLI which can safely point into #3-style compacting GC heaps. See section 3.3 of my paper A Design Rationale for C++/CLI for more rationale about ^ and gcnew.

Other GC Resources

For a wonderful 57-minute conversation on garbage collection by one of the world’s top GC experts, run don’t walk to the C9 “Inside Garbage Collection” interview with Patrick Dussud. Patrick wrote the .NET CLR’s GC, and it was far from his first; before that he had deep experience implementing Lisp runtimes, and I’m sure has forgotten more about GC than I’ll ever know. He’s also a great guy to work with.

For a great book on GC, I love Garbage Collection by Jones and Lins.

John McCarthy

image

What a sad, horrible month. First Steve Jobs, then Dennis Ritchie, and now John McCarthy. We are losing many of the greats all at once.

If you haven’t heard of John McCarthy, you’re probably learning about his many important contributions now. Some examples:

  • He’s the inventor of Lisp, the second-oldest high-level programming language, younger than Fortran by just one year. Lisp is one of the most influential programming languages in history. Granted, however, most programmers don’t use directly Lisp-based languages, so its great influence has been mostly indirect.
  • He coined the term “artificial intelligence.” Granted, however, AI has got a bad rap from being oversold by enthusiasts like Minsky; for the past 20 years or so it’s been safer to talk in euphemisms like “expert systems.” So here too McCarthy’s great influence has been less direct.
  • He developed the idea of time-sharing, the first step toward multitasking. Okay, now we’re talking about a contribution that’s pretty directly influential to our modern systems and lives.

But perhaps McCarthy’s most important single contribution to modern computer science is still something else, yet another major technology you won’t hear nearly enough about as being his invention:

Automatic garbage collection. Which he invented circa 1959.

No, really, that’s not a typo: 1959. For context, that year’s first quarter alone saw the beginning of the space age as Sputnik 1 came down at the end of its three-month orbit; Fidel Castro take Cuba; Walt Disney release Sleeping Beauty; The Day the Music Died; the first Barbie doll; and President Eisenhower signing a bill to enable Hawaii to become a state.

GC is ancient. Electronic computers with core memory were still something of a novelty (RAM didn’t show up until a decade or so later), machine memory was measured in scant kilobytes, and McCarthy was already managing those tiny memories with automatic garbage collection.

I’ve encountered people who think GC was invented by Java in 1995. It was actually invented more than half a century ago, when our industry barely even existed.

Thanks, John.

And here’s hoping we can take a break for a while from writing these memorials to our giants.

Your First C Program

As a tribute in honor of Dennis Ritchie’s passing, I’d like to invite you to share your thoughts in this post’s comments about your first C program – either the code if you remember it approximately, or a story about when you wrote it.

Here’s mine.

I wrote my first C program in 1988 as a lab assignment for a fourth-year course in computer graphics at the University of Waterloo. In the first day or two of the course, our prof gave us our first assignment: Write a program that displays and controls a 3D animated robot with moving head, arms, and legs. Successive assignments would let us swoop around him, controlling point of view and zoom with a mouse, and other nifty features, but the first assignment was just to get him on-screen and capable of a little basic motion.

Oh, and the program was to be written:

  • to run on one of the lab’s four brand-new SGI IRIS workstations (oh, here’s the manual);
  • using a custom UofW internal library (oh, here’s the manual);
  • in C (we assume you know it, use man to learn this compiler’s command line switches if you need to);

and it’s due in a few days. I can’t remember exactly now, but I think we had something like five days. After all, this was just a warm-up initial exercise for the course.

Here’s the thing: I had never used C. Never even seen it.

Oh, I’d used many different languages in my undergrad career, from Cobol to Pascal to Prolog to 6809 assembler and many points between, but just never C. Don’t get the wrong impression, C was already used widely at UofW at the time and most of the other undergrads in the class knew it, but by some freak of course selection combined with professor allocation I somehow had managed to come across pretty much everything but C so far for the first three years.

Fortunately, there was K&R.

Armed with K&R and a printed-out C tutorial, I had a few days to learn a new language (huh? whaddayamean #include? oh, okay…), an unfamiliar compiler, an unfamiliar graphics library, and the quirks of this particular flavor of Unix – to produce a working program in an unfamiliar domain with unfamiliar concepts (graphics). And only that last bit was the actual topic material for the course. The language, compiler, library, etc. was just uninteresting scaffolding you were expected to know or just pick up on the fly, don’t bother the professor with questions about those when you can look it all up yourself.

I don’t remember what mark I got on the assignment, but the code worked.

I was glad that C was easy to learn, and that its manual in the form of K&R was so clear to read and understand. Thanks again, Dennis.

2000 Interview: Dennis Ritchie, Bjarne Stroustrup, and James Gosling

Ritchie, Stroustrup, and Gosling

Dennis Ritchie gave very few interviews, but I was lucky enough to be able to get one of them.

Back in 2000, when I was editor of C++ Report, I interviewed the creators of C, C++, and Java all together:

The C Family of Languages: Interview with Dennis Ritchie, Bjarne Stroustrup, and James Gosling

This article appeared in Java Report, 5(7), July 2000 and C++ Report, 12(7), July/August 2000.

Their extensive comments — on everything from language history and design (of course) and industry context and crystal-ball prognostication, to personal preferences and war stories and the first code they ever wrote — are well worth re-reading and remarkably current now, some 11 years on.

As far as I know, it’s the only time these three have spoken together. It’s also the only time a feature article ran simultaneously in both C++ Report and Java Report.

Grab a cup of coffee, fire up your tablet, and enjoy.