Articles & Books

AllocatorAwareContainer: Introduction and pitfalls…—Jonathan Müller

An interesting article about some dangerous allocators:

AllocatorAwareContainer: Introduction and pitfalls of propagate_on_container_XXX defaults

by Jonathan Müller

From the article:

While I was writing the std_allocator adapter of foonathan/memory I've learned some not so well-known facts about the STL Allocator and AllocatorAwareContainer concepts I'd like to share. Let's take a deep breath and dive in into an aspect of the STL containers that isn't that well covered: Allocator storage.

I will explain the comparison properties of Allocators, show the C++11 propagate_on_container_XXX traits and how the combination of the two can lead to an unnecessary pessimization and a probably not widely known case of undefined behavior...

C++ User Group Meetings in October

The monthly overview on upcoming user group meetings:

C++ User Group Meetings in October

by Jens Weller

From the article:

    5.10 C++ UG Dublin - C/C++ Meeting with 3 Talks
    7.10 C++ UG Saint Louis - Intro to Unity\, Scott Meyers "gotchas"\, Group exercise
    7.10 C++ UG Washington, DC - Q & A / Info Sharing
    13.10 C++ UG New York - Joint October C++ Meetup with Empire Hacking
    14.10 C++ UG Utah - Regular Monthly Meeting
    14.10 C++ UG San Francisco/ Bay area - Presentation and Q&A
    19.10 C++ UG Austin - North Austin Monthly C/C++ Pub Social
    20.10 C++ UG Berlin - Thomas Schaub - Introduction to SIMD
    20.10 C++ UG Hamburg - JavaX (really?)
    21.10 C++ UG Washington, DC - Q & A / Info Sharing
    21.10 C++ UG Bristol - Edward Nutting
    21.10 C++ UG Düsseldorf - CppCon trip report & Multimethods
    21.10 C++ UG Arhus - Lego & C++
    24.10 C++ UG Italy - Clang, Xamarin, MS Bridge, Google V8
    28.10 C++ UG San Francisco/ Bay area - Workshop and Discussion Group
    29.10 C++ UG Bremen - C++ User Group

This years C++ Committee papers sorted by mailing and subgroup

An alternative listing of the papers sorted by mailing & subgroups:

This years C++ Committee papers sorted by mailing and subgroup

by Jens Weller

From the article:

I used to do overviews on all papers for a meeting, and when I find the time, I will do this for upcoming meetings again. I will try to post a best-of later, with all the good stuff on concepts, modules and more later. Currently I'm to busy, I just got back from CppCon, and will go to the Qt World Summit next week (meet me there!).

So, in the mean time you can take take a look for yourself, as what follows is the list off all papers submitted this year, sorted by mailings and then subgroups. My awesome paper crawler tool did finally its job correct...

The Problem, The Culprits, The Hope—Tony “Bulldozer00” (BD00) DaSilva

This is another call to all C++ programmers, it is time to change!

The Problem, The Culprits, The Hope

by Tony “Bulldozer00” (BD00) DaSilva

From the article:

Bjarne Stroustrup’s keynote speech at CppCon 2015 was all about writing good C++11/14 code. Although “modern” C++ compilers have been in wide circulation for four years, Bjarne still sees:

I’m not an elite, C++ committee-worthy, programmer, but I can relate to Bjarne’s frustration...

Bitesize Modern C++ : noexcept—Glennan Carnie

What is the use of noexcept?

Bitesize Modern C++ : noexcept

by Glennan Carnie

From the article:

We have some basic problems when trying to define error management in C:

  • There is no “standard” way of reporting errors. Each company / project / programmer has a different approach
  • Given the basic approaches, you cannot guarantee the error will be acted upon.
  • There are difficulties with error propagation; particularly with nested calls.

The C++ exception mechanism gives us a facility to deal with run-time errors or fault conditions that make further execution of a program meaningless...

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.


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());
    } // 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.