C++11: A cheat sheet -- Alex Sinyakov

Want a quick "cheat sheet" overview of what's new in C++11? Alex Sinyakov recently gave a presentation on this topic and has posted slides that are useful as a capsule summary in flash card form:

C++11 (PDF slides)

Alex Sinyakov, AMC Bridge LLC

Slide after slide shows C++11 code side by side with the same code written in older C++ style or in other languages. You'll quickly notice a pattern: In example after example, C++11 code is clean, safe, and as fast as ever... and sometimes even faster.

As Bjarne Stroustrup puts it: "Surprisingly, C++11 feels like a new language: The pieces just fit together better than they used to and I find a higher-level style of programming more natural than before and as efficient as ever."

Enjoy these great quick study notes as a refresher before your next C++11 interview.

For a detailed treatment of what’s new in C++11, see Overview of the New C++ (C++11) by Scott Meyers, featured on our Get Started! page. These are Scott’s fully-annotated color training materials from his course of the same name, and the best current approximation of “a book on what’s new in C++11.” (Free sample available.)

Best of 2012: auto

Perhaps the most common single question about C++11 is: When should we use auto to declare local variables?

Here's a current set of responses on Programmers.StackExchange. Enjoy.

Does auto make C++ code harder to understand?

I saw a conference by Herb Sutter where he encourages every C++ programmer to use auto.

I had to read C# code some time ago where var was extensively used and the code was very hard to understand -- every time var was used I had to check the return type of the right side. Sometimes more than once, because I forgot the type of the variable after a while!

I know the compiler knows the type and I don’t have to write it, but it is widely accepted that we should write code for programmers, not for compilers.

I also know that is more easy to write:

auto x = GetX();

Than:

 

someWeirdTemplate<someOtherVeryLongNameType, ...>::someOtherLongType x = GetX();

But this is written only once and the GetX() return type is checked many times to understand what type x has.

This made me wonder -- does auto make C++ code harder to understand?

Continue reading...

Quick Q: Inserting a variadic argument list into a vector? -- StackOverflow

From StackOverflow [c++11]:

I have an object that needs to take a variadic argument list in its constructor and store the arguments in a vector. How do I initialize a vector from a the arguments of a variadic constructor?

class GenericNode {
public:
    GenericNode(GenericNode*... inputs) {
            /* Something like... */
        // inputs_.push_back(inputs)...;
}
private:
    std::vector<GenericNode*> inputs_;
};

Continue reading...

Best of 2012: Clang @ GoingNative -- Chandler Carruth

As we're all unwinding at the end of the year, your blog staff would like to recommend watching again one of the year's most hilariously entertaining and deeply informative talks about the world's hottest new C++ compiler -- a holiday video that's genuinely fun:

Clang: Defending C++ from Murphy's Million Monkeys

by Chandler Carruth
at GoingNative 2012

[... Clang] provides fantastic diagnostics, static and dynamic program analysis, advanced rewriting and refactoring functionality, and language extensibility. Together with improvements to the language in C++11 these help programmers cope with today's code and write better code tomorrow. Clang also makes it easier than ever before to evolve and evaluate new language features and extensions to make C++ itself better.

Through this talk I'll give some background on the Clang compiler, what it does today to make writing C++ better, and how we're using it to help shape the C++ language going forward.

Even your non-technical family and friends will probably enjoy the first five minutes.

Thanks again to Chandler, GoingNative, and Channel 9 for an engaging and illuminating presentation.

 

Clang 3.2 released

Chris Lattner has announced the release of version 3.2 of the Clang C++ compiler, as part of LLVM 3.2. Read the release notes here.

Highlights include:

  • Improved error and warning diagnostics.
  • Doxygen-like documentation comment support.
  • Improved Python bindings.
  • Standard C11 _Alignof support
  • The same strong Standard C++11 support as in the spring release, Clang 3.1. See the C++98 and C++11 Support in Clang status page for details.

Quick Q: Simultaneously iterating over and modifying an unordered_set? -- StackOverflow

From StackOverflow [c++11]:

Consider the following code:

unordered_set<T> S = ...;
for (const auto& x : S)
   if (...)
       S.insert(...);

This is broken correct? If we insert something into S then the iterators may be invalidated (due to a rehash), which will break the range-for because under the hood it is using S.begin ... S.end.

Is there some pattern to deal with this?

Continue reading...

Three Optimization Tips for C++ -- Andrei Alexandrescu

For your Friday viewing pleasure, from the always-engaging master, Andrei Alexandrescu:

Three Optimization Tips for C++ (video) (PDF slides)

Andrei Alexandrescu

Facebook NYC, December 4, 2012

 

From an early slide in the talk: "Intuition:

  • Ignores aspects of a complex reality
  • Makes narrow/wrong/obsolete assumptions

[...]

  • The only good intuition: "I should time this."

​Enjoy.

(Bonus: The tips are also applicable in other languages. They just happen to be easier to use and control in C++.)

An implementation of generic lambdas (request for feedback) -- Faisal Vali

This week, Faisal Vali shared an initial "alpha" implementation of generic lambdas in Clang. Faisal is the lead author of the proposal (N3418), with Herb Sutter and Dave Abrahams.

To read and participate in the active discussion, see the message thread on std-proposals.

Here is a copy of Faisal's announcement:

Motivated by the positive feedback we received regarding Generic Lambdas (during the October 2012 ISO C++ Standards Meeting in Portland), I have implemented a reasonably complete (unless I am missing something obvious) implementation (http://faisalv.github.com/clang-glambda/) of most of the proposal (named lambda syntax for functions has not been attempted) using a fork of Clang.

 

We would like to encourage developers who are interested in this feature, to either compile the code or download the binaries (sorry, only Windows for now) and play with the implementation and provide us with feedback so that we can incorporate it within our next revision of the document.

The following link: http://faisalv.github.com/clang-glambda/, has some instructions (towards the bottom) on how to compile the code or use the binaries for Windows.

 

Any and all constructive feedback will be greatly appreciated.

The current version (12/2012) implements subproposals 2.1, 2.2, 2.3 and 2.5.

 

2.1 Allow the type-specifier within a parameter declaration of a lambda to be auto (i.e. auto is mandatory)

auto Sum = [](auto a, decltype(a) b) { return a + b; };
int i = Sum(3, 4);
double d = Sum(3.14, 2.77);

 

2.2 Allow the use of familiar template syntax in lambda expressions

auto NumElements = []<int N>(auto (&a)[N]) { return N; };
int arri[]{1, 2, 3};
double arrd[]{3.14, 2.77, 6.626};
auto total = NumElements(arri) + NumElements(arrd);

 

2.3 Permit a lambda body to be an expression

int local = 10;
auto L = [&](auto a) a + ++local;

 

2.5 Autogenerate a conversion to function pointer in captureless generic lambdas

auto L = [](auto a, decltype(a) b) { return a + b; };
int (*fp)(int, int) = L;

 

Thank you and looking forward to the feedback!

Is C++11 uniform initialization a replacement for the old style syntax? -- Programmers.StackExchange

Here is a question from Programmer's StackExchange (tags [c++] and [c++11]) which most C++ developers, whatever their level, will ask as soon as they are introduced to the new Uniform Initialization syntax:

Is it recommended now to use uniform initialization in all cases? What should the general approach be for this new feature as far as coding style goes and general usage? What are some reasons to not use it?

The accepted answer clearly provides very good reasons to use this new syntax as much as possible (if your compiler supports it already): minimizing redundant typenames and avoiding the Most Vexing Parse. It also points some reasons to not use this syntax, in particular in case you're trying to call a standard container constructor.

There is one other reason not to:

std::vector<int> v{100};

What does this do? It could create a vector<int> with one hundred default-constructed items. Or it could create a vector<int> with one item whose value is 100. ... In actuality, it does the latter.

Read the full QA.

Read Stroustrup's FAQ about Uniform Initialization syntax.

Bjarne Stroustrup interview: From the Foundation and C++11, to portability and the C++ resurgence

Last Monday, Bjarne Stroustrup gave a live interview to David Intersimone of Embarcadero to kick off their CodeRage 7 conference. Bjarne discusss the new Standard C++ Foundation, the ISO C++11 standard, new language features, how C++11 builds on C++’s strengths, application portability, and C++’s ubiquitous presence in the markets.

The video is now on YouTube. Enjoy.