September 2015

Video available: Bjarne Stroustrup, "Writing Good C++14" -- CppCon 2015 opening keynote

stroustrup-cppcon2015-v.jpgCppCon is in full swing, and once again all the sessions, panels, and lightning talks are being professionally recorded and will be available online -- about a month after the conference, because it takes time to process over 100 talks!

However, because of the importance of Bjarne's open keynote announcements on Monday, the team has pulled out the stops to process his video and get it up on YouTube (and maybe soon also Channel 9 for areas where YouTube is not available). It's there now, so if you couldn't be at CppCon on Monday in person, check it out:

Writing Good C++14 (YouTube) (slides)

by Bjarne Stroustrup, CppCon 2015 opening keynote

Related: Bjarne Stroustrup announces C++ Core Guidelines

The team says that they may also fast-track the other daily keynote/plenary sessions as well, some of which are directly related to Bjarne's keynote. If that happens, we'll post links here too. In the meantime, enjoy Bjarne's groundbreaking talk -- as one CppCon attendee and longtime C++-er said, "this is one of the most exciting weeks for C++ I can remember." We agree.

Bjarne Stroustrup announces C++ Core Guidelines

This morning in his opening keynote at CppCon, Bjarne Stroustrup announced the C++ Core Guidelines (github.com/isocpp/CppCoreGuidelines), the start of a new open source project on GitHub to build modern authoritative guidelines for writing C++ code. The guidelines are designed to be modern, machine-enforceable wherever possible, and open to contributions and forking so that organizations can easily incorporate them into their own corporate coding guidelines.

The initial primary authors and maintainers are Bjarne Stroustrup and Herb Sutter, and the guidelines so far were developed with contributions from experts at CERN, Microsoft, Morgan Stanley, and several other organizations. The guidelines are currently in a “0.6” state, and contributions are welcome. As Stroustrup said: “We need help!”

Stroustrup said: “You can write C++ programs that are statically type safe and have no resource leaks. You can do that without loss of performance and without limiting C++’s expressive power. This supports the general thesis that garbage collection is neither necessary nor sufficient for quality software. Our core C++ guidelines makes such code simpler to write than older styles of C++ and the safety can be validated by tools that should soon be available as open source.”

From Stroustrup’s talk abstract:

In this talk, I describe a style of guidelines that can be deployed to help most C++ programmers... The rules are prescriptive rather than merely sets of prohibitions, and about much more than code layout... The core guidelines and a guideline support library reference implementation will be open source projects freely available on all major platforms (initially, GCC, Clang, and Microsoft).

Although the repository was not officially announced until today, it was made public last week and was noticed: CppCoreGuidelines was the #1 trending repository worldwide on GitHub on Friday, and is currently the #1 trending repository worldwide for the past week, across all languages and projects.

Stroustrup also announced two other related projects.

Guideline Support Library (GSL): First, the C++ Core Guidelines also specifies a small Guideline Support Library (GSL), a set of common types like array_view and not_null to facilitate following the modern guidelines. An initial open source reference implementation contributed and supported by Microsoft is now available on GitHub at github.com/Microsoft/GSL. It is written in portable C++ that should work on any modern compiler and platform, and has been tested on Clang/LLVM 3.6 and GCC 5.1 for Linux, with Xcode and GCC 5.2.0 for OS X, and with Microsoft Visual C++ 2013 (Update 5) and 2015 for Windows. This is both a supported library and an initial reference implementation; other implementations by other vendors are encouraged, as are forks of and contributions to this implementation.

Checker tool: Second, the C++ Core Guidelines are designed to be machine-enforceable wherever possible, and include many rules that can be checked by a compiler, lint, or other tool. An initial implementation based on Microsoft’s Visual Studio will be demonstrated in several talks at CppCon this week, including Herb Sutter’s Day 2 plenary session tomorrow morning. This implementation will be made available as a Windows binary in October, with the intention to open source the implementation thereafter. This too will become a supported tool and an initial reference implementation open to others; other implementations by other vendors of compilers, linters, and other tools are encouraged.

A number of other CppCon talks will go deeper into the related topics, notably the following talks by speakers who collaborated on the Guidelines effort:

Herb Sutter: Writing Good C++14 by Default (Tue 10:30am)

Gabriel Dos Reis: Large Scale C++ with Modules: What You Should Know (Tue 2:00pm)

Neil MacIntosh: More Than Lint: Modern Static Analysis for C++ (Wed 2pm)

Neil MacIntosh: A Few Good Types: Evolving array_view and string_view for Safe C++ Code (Wed 3:15pm)

Gabriel Dos Reis: Contracts for Dependable C++ (Wed 4:45pm)

Eric Niebler: Ranges and the Future of the STL (Fri 10:30am)

(and more)

If you’re at CppCon this week, watch for those talks. If you aren’t, like last year’s event, CppCon 2015 is again professionally recording all talks, and they will be freely available online about a month after the conference.
 

The Visual C++ team is at CppCon 2015 by Eric Battalio

CppCon 2015 starts in two hours:

The Visual C++ team is at CppCon 2015

by Eric Battalio

From the article:

Steve Carroll and Ayman Shoukry cover what's new in VC++ early on Thursday morning. Ankit Asthana and Marc Gregoire will update us on the [Clang-based] support for cross-platform mobile development in VS 2015... James Radigan will talk about the work that we're doing to connect the Clang front end to the Microsoft optimizing back end [and] how we're working with the community to make this possible... Gabriel Dos Reis will talk about C++ Modules, a new design that helps with componentization, isolation from macros, scalable build, and support for modern semantics-aware developer tools. ...

Stephan T. Lavavej will discuss developments in <functional> from C++11 to C++17. We'll hear about contracts from Gabriel Dos Reis, and ... Artur Laksberg goes into the details of the Concurrency TS while Gor Nishanov describes the exciting future of concurrency in C++: coroutines, an abstraction that makes your code both simpler and execute faster. ...

You might have noticed a new repo that the Standard C++ Foundation published last week: the C++ Core Guidelines... Bjarne will talk about this in his keynote on Monday morning, and Herb Sutter will continue the discussion with his talk on Tuesday. And we've not only been working on the guidelines: we've implemented a library to support the guidelines and enforcement tools that automatically verify that your code follows them. Neil MacIntosh will discuss both of these projects in his back-to-back talks on Wednesday afternoon. The C++ Core Guidelines are a huge step forward for the language and the Visual C++ team is excited to be part of the group working on bringing them to reality!

C++ Core Guidelines -- Bjarne Stroustrup, Herb Sutter

Bjarne Stroustrup and Herb Sutter are currently editing the newly created C++ Core Guidelines on GitHub. 

C++ Core Guidelines

From the abstract section of the page:

This document is a set of guidelines for using C++ well. The aim of this document is to help people to use modern C++ effectively. By "modern C++" we mean C++11 and C++14 (and soon C++17). In other words, what would you like your code to look like in 5 years' time, given that you can start now? In 10 years' time?

The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management, and concurrency. Such rules affect application architecture and library design. Following the rules will lead to code that is statically type safe, has no resource leaks, and catches many more programming logic errors than is common in code today. And it will run fast - you can afford to do things right.

We are less concerned with low-level issues, such as naming conventions and indentation style. However, no topic that can help a programmer is out of bounds.

Our initial set of rules emphasize safety (of various forms) and simplicity. They may very well be too strict. We expect to have to introduce more exceptions to better accommodate real-world needs. We also need more rules.

You will find some of the rules contrary to your expectations or even contrary to your experience. If we haven't suggested you change your coding style in any way, we have failed! Please try to verify or disprove rules! In particular, we'd really like to have some of our rules backed up with measurements or better examples.

You will find some of the rules obvious or even trivial. Please remember that one purpose of a guideline is to help someone who is less experienced or coming from a different background or language to get up to speed.

The rules are designed to be supported by an analysis tool. Violations of rules will be flagged with references (or links) to the relevant rule. We do not expect you to memorize all the rules before trying to write code.

The rules are meant for gradual introduction into a code base. We plan to build tools for that and hope others will too.

Comments and suggestions for improvements are most welcome. We plan to modify and extend this document as our understanding improves and the language and the set of available libraries improve.

 

CppCon 2014 Unicode in C++--James McNellis

Have you registered for CppCon 2015 in September? Don’t delay – Registration is open now.

While we wait for this year’s event, we’re featuring videos of some of the 100+ talks from CppCon 2014 for you to enjoy. Here is today’s feature:

Unicode in C++

by James McNellis

(watch on YouTube) (watch on Channel 9)

Summary of the talk:

In some programming languages, text processing is easy. Unfortunately, C++ is not one of those languages. C++ lacks good, built-in support for Unicode, though the situation is starting to improve.

This session will begin with a brief overview of text encodings, and an introduction to Unicode and the various Unicode encodings. We'll look at the woeful state of Unicode support in C++98 (or, really, lack thereof), then take a look at the improvements that were made in C++11 and other improvements that have recently been proposed for standardization. We'll finish up with a discussion of several libraries designed to make it easier to work with Unicode in C++, including the widely-used, open-source International Components for Unicode (ICU) library.

CppCast Episode 27: VR Development with Nicolas Lazeraff

Episode 27 of CppCast the only podcast for C++ developers by C++ developers. In this episode Rob and Jason are joined by Nicolas Lazaraff to discuss the current state of VR development with C++.

CppCast Episode 27: VR Development with Nicolas Lazareff

by Rob Irving and Jason Turner

About the interviewee:

Nicolas Lazareff is a VR/AR engineer who is passionate about bridging the interface between computers and humans. Currently he's VP of Software Development at OTOY focusing on VR and AR ("mixed/digital reality"). He was a cofounder of everyAir, a pioneering P2P game streaming application which was later acquired. Before that he worked at Microsoft on Office 2010 and 2013.

CppCon 2015 Program Highlights, 15 of N

The CppCon 2015 conference program has been posted for the upcoming September conference. We’ve received requests that the program continue to be posted in “bite-sized” posts, a few sessions at a time, to make the 100+ sessions easier to absorb, so here is another set of talks. This series of posts will conclude once the entire conference program has been posted in this way.

 

The following interrelated CppCon 2015 talks tackle interesting issues and more.

In this post:

  • Grill the Committee
  • C++ on the Web: ponies for developers without pwn’ing users
  • Implementation of a component-based entity system in modern C++14
  • The Current State of (free) Static Analysis
  • Stop Teaching C
  • Applying functional programming in code design

 

Grill the Committee with Jon KalbChandler CarruthMarshall ClowLawrence CrowlGabriel Dos ReisRichard SmithBjarne StroustrupHerb SutterVille Voutilainen and Michael Wong

What would you like to know about how the C++ Standard happens?

The panel is made up of members of the C++ Standards Committee and the audience asks the questions.


C++ on the Web: ponies for developers without pwn’ing users by JF Bastien, Jest-in-Time Compiler, Google

Is it possible to write apps in C++ that run in the browser with native code speed? Yes. Can you do this without the security problems associated with running native code downloaded from the net? Yes and yes. Come to this session to learn how.

We'll showcase some resource-intensive applications that have been compiled to run in the browser. These applications run as fast as native code with access to cornerstone native programming APIs—modern C++ STL, OpenGL, files and processes with full access to C++’s concurrency and parallelism—all in an architecture- and OS-agnostic packaging. Then, we'll describe how we deliver native code on the web securely, so developers get their C++ ponies and users don’t get pwn’d. We’ll also touch on the fuzzing, code randomization, and sandboxing that keep the billions of web users safe.


Implementation of a component-based entity system in modern C++14 by Vittorio Romeo

An alternative to deep inheritance trees for game and application architecture design is "composition". Separating data (in independent components) from logic (in independent systems) allows the code to be more reusable and more efficient, alongside additional benefits. Using modern C++11 and C++14 features, it is possible to design an efficient and user-friendly component-based entity system library, with intuitive syntax and convenient cost-free abstractions.


The Current State of (free) Static Analysis by Jason Turner

We will discuss the currently available free static analysis software available for C++. What kinds of errors can these tools catch? What kind do they miss? Why static analysis should be a part of your normal build process.


Stop Teaching C by Kate Gregory, Partner, Gregory Consulting

To this day most people who set out to help others learn C++ start with "introduction to C" material. I think this actively contributes to bad C++ code in the world. For the past few years I've been teaching C++ (and making suggestions to folks who intend to teach themselves) in an entirely different way. No char* strings, no strlen, strcmp, strcpy, no printf, and no [] arrays. Pointers introduced very late. References before pointers, and polymorphism with references rather than with pointers. Smart pointers as the default pointer with raw pointers (whether from new or &) reserved for times they're needed. Drawing on the Standard Library sooner rather than later, and writing modern C++ from lesson 1.

In this session I want to talk about the specific advantages of teaching C++ this way – a way that’s very different from the way you almost certainly learned the language. You’ll be pleasantly surprised to see what you get to leave for later or never cover at all, what bad habits you don't later need to correct, what complicated concepts actually become accessible to beginners, and how you spend a lot less time dictating magic spells you can't explain yet, and more showing someone a comprehensive, sensible, and understandable language.

You don't have to be a trainer to come to this session. If you ever mentor other developers and show them your C++ code, if you ever help somebody choose a book or a course or other material to learn from, or even if you occasionally feel bad that you work in a language that's hard to learn, come and see how one philosophical shift can turn that very same language into one that's actually pretty easy to learn!


Applying functional programming in code design by Michał Dominiak, Software Engineer, Nokia Networks

At first glance C++ doesn't seem to be a language that lets you do much functional programming, not to mention actually focusing the structure of your application around that. But that is changing, together with the general approach to program in the language. We do care about const-correctness; when writing code meant to run concurrently, we want to avoid locks, so we do our best not to share mutable state (I'm here to argue that uniquely owned mutable state is perfectly fine). With that mindset, we can try to design our applications in a functional way.

This talk will focus not only on things typically associated with functional programming, but also on the following in the context of C++: * Making functions pure (as long as it makes sense). * Using functional data structures. * Designing control flows that don't lead to shared state. * Composability and benefiting from laziness. * Striving for generic code. * Noticing patterns and turning them into abstractions. * Functors and monads as "patterns". * An example application built around those principles.

Quick Q: What is a smart pointer and when should I use one?

Quick A: Pointers that helps you manage memory.

Recently on SO:

What is a smart pointer and when should I use one?

A smart pointer is a class that wraps a 'raw' (or 'bare') C++ pointer, to manage the lifetime of the object being pointed to. There is no single smart pointer type, but all of them try to abstract a 'raw' pointer in a practical way.

Smart pointers should be preferred over 'raw' pointers. If you feel you need to use pointers (first consider if you really do) you would normally want to use a smart pointer as this can alleviate many of the problems with 'raw' pointers, mainly forgetting to delete the object and leaking memory.

With 'raw' C++ pointers, the programmer has to explicitly destroy the object when it is no longer useful.

// Need to create the object to achieve some goal
MyObject* ptr = new MyObject();
ptr->DoSomething(); // Use the object in some way
delete ptr; // Destroy the object. Done with it.
// Wait, what if DoSomething() raises an exception...?

A smart pointer by comparison defines a policy as to when the object is destroyed. You still have to create the object, but you no longer have to worry about destroying it.

SomeSmartPtr<MyObject> ptr(new MyObject());
ptr->DoSomething(); // Use the object in some way.

// Destruction of the object happens, depending
// on the policy the smart pointer class uses.

// Destruction would happen even if DoSomething()
// raises an exception

The simplest policy in use involves the scope of the smart pointer wrapper object, such as implemented by boost::scoped_ptr or std::unique_ptr.

void f()
{
    {
       boost::scoped_ptr<MyObject> ptr(new MyObject());
       ptr->DoSomethingUseful();
    } // boost::scopted_ptr goes out of scope --
      // the MyObject is automatically destroyed.

    // ptr->Oops(); // Compile error: "ptr" not defined
                    // since it is no longer in scope.
}

Note that scoped_ptr instances cannot be copied. This prevents the pointer from being deleted multiple times (incorrectly). You can, however, pass references to it around to other functions you call.

Scoped pointers are useful when you want to tie the lifetime of the object to a particular block of code, or if you embedded it as member data inside another object, the lifetime of that other object. The object exists until the containing block of code is exited, or until the containing object is itself destroyed.

A more complex smart pointer policy involves reference counting the pointer. This does allow the pointer to be copied. When the last "reference" to the object is destroyed, the object is deleted. This policy is implemented by boost::shared_ptr and std::shared_ptr.

void f()
{
    typedef std::tr1::shared_ptr<MyObject> MyObjectPtr; // Nice short alias.
    MyObjectPtr p1; // Empty
    {
        MyObjectPtr p2(new MyObject());
        // There is now one "reference" to the created object
        p1=p2; // Copy the pointer.
        // There are now two references to the object.
    } // p2 is destroyed, leaving one reference to the object.
} // p1 is destroyed, leaving a reference count of zero.
  // The object is deleted.

Reference counted pointers are very useful when the lifetime of your object is much more complicated, and is not tied directly to a particular section of code or to another object.

There is one drawback to reference counted pointers — the possibility of creating a dangling reference:

// Create the smart pointer on the heap
MyObjectPtr* pp = new MyObjectPtr(new MyObject())
// Hmm, we forgot to destroy the smart pointer,
// because of that, the object is never destroyed!
Another possibility is creating circular references:

struct Owner {
   boost::shared_ptr<Owner> other;
};

boost::shared_ptr<Owner> p1 (new Owner());
boost::shared_ptr<Owner> p2 (new Owner());
p1->other = p2; // p1 references p2
p2->other = p1; // p2 references p1

// Oops, the reference count of of p1 and p2 never goes to zero!
// The objects are never destroyed!

To work around this problem, both Boost and C++11 have defined a weak_ptr to define a weak (uncounted) reference to a shared_ptr.

This answers is rather old, and so uses what was 'good' at the time, which was smart pointers provided by the boost library. Since C++11 the standard library has provided sufficient smart pointers types, and so you should favour the use of std::unique_ptr, std::shared_ptr and std::weak_ptr.

There is also std::auto_ptr. It is very much like a scoped pointer, except that it also has the "special" dangerous ability to be copied — which also unexpectedly transfers ownership! It is deprecated in the newest standards, so you shouldn't use it.

std::auto_ptr<MyObject> p1 (new MyObject());
std::auto_ptr<MyObject> p2 = p1; // Copy and transfer ownership.
                                 // p1 gets set to empty!
p2->DoSomething(); // Works.
p1->DoSomething(); // Oh oh. Hopefully raises some NULL pointer exception.

Should you be using something instead of what you should use instead?--Scott Meyers

The title is confusing, the article is not and should be read!

Should you be using something instead of what you should use instead?

by Scott Meyers

From the article:

The April 2000 C++ Report included an important article by Matt Austern: "Why You Shouldn't Use set—and What to Use Instead." It explained why lookup-heavy applications typically get better performance from applying binary search to a sorted std::vector than they'd get from the binary search tree implementation of a std::set. Austern reported that in a test he performed on a Pentium III using containers of a million doubles, a million lookups in a std::set took nearly twice as long as in a sorted std::vector...