Tag Archives: Stroustrup

C++14 Language Extensions

Whilst reading Scott Meyers’ Effective Modern C++, I was looking for some clarification on ‘generalised lambda capture’ and came across this C++ 14 feature list. It was interesting to compare to the list of expected features that Bjarne Stroustrup presented at the ACCU 2013 conference – he described all of the following, which made it into C++14:

  • Generalised return type deduction for normal functions, not just lambdas
  • Generic (polymorphic) lambdas
  • Generalised constexpr functions (listed as Extended constexpt on the feature list)
  • Binary Literals
  • Digit Separators
  • Deprecated Attribute

However, this one appears not to have made the cut:

  • Runtime-sized arrays

This would be a great new feature and I blogged about it at the time – but it appears the work has stalled.

Leave a comment

Filed under C++, Programming

Interview with Bjarne Stroustrup

Short interview with Bjarne Stroustrup where he comments briefly on Go and Swift.

Apparently, Stroustrup is currently working for Morgan Stanley – hence his interest in C++ for financial applications.

Leave a comment

Filed under C++, Programming

C++11 noexcept

Someone on ISOCpp re-awakened an old question on StackOverflow about noexcept, dynamic v static checking and differences between noexcept and the (now deprecated) throw specifiers.

Throw specifiers were the subject of Item 14 – Use Exception Specifications Judiciously in Scott Meyers’ More Effective C++. The drawbacks he mentions are: the standard prohibits compilers from rejecting calls to functions that might violate the exception specification (including if there is no specifier on the called function – this to allow integration with legacy code libraries that lack such specifications); you cannot know anything about the exceptions thrown by a template’s type parameters – so templates and exception specifications don’t mix; they’re easy to violate inadvertently (e.g. via callback functions); they lead to abrupt program termination when violated.

Stroustrup wrote this about noexcept in his C++11 FAQ:

If a function declared noexcept throws (so that the exception tries to escape the noexcept function) the program is terminated (by a call to terminate()). The call of terminate() cannot rely on objects being in well-defined states (i.e. there is no guarantees that destructors have been invoked, no guaranteed stack unwinding, and no possibility for resuming the program as if no problem had been encountered). This is deliberate and makes noexcept a simple, crude, and very efficient mechanism

This post gives a history of noexcept,

If the noexcept feature appears to you incomplete, prepared in a rush, or in need of improvement, note that all C++ Committee members agree with you. The situation they faced was that a safety problem with throwing move operations was discovered in the last minute and it required a fast solution

There are however important differences [between noexcept and throw()]. In case the no-throw guarantee is violated, noexcept will work faster: it does not need to unwind the stack, and it can stop the unwinding at any moment (e.g., when reaching a catch-all-and-rethrow handler). It will not call std::unexpected. Next, noexcept can be used to express conditional no-throw, like this: noexcept(some-condition)), which is very useful in templates, or to express a may-throw: noexcept(false).

One other non-negligible difference is that noexcept has the potential to become statically checked in the future revisions of C++ standard, whereas throw() is deprecated and may vanish in the future.

and this comment on SO from Jonathan Wakely also makes sense:

template code such as containers can behave differntly based on the presence or absence of noexcept (and equivalently throw()) so it’s not just about compiler optimizations, but also impacts library design and choice of algorithm. The key to doing that is the noexcept operator that allows code to query how throwy an expression is, that’s the new thing, and all that cares about is a yes/no answer, it doesn’t care what type of exception might be thrown, only whether one might be thrown or not

Leave a comment

Filed under C++

Bjarne Stroustrup’s Tour of C++

I’m reading through Bjarne Stroustrup’s Tour of C++, which Addison-Wesley have graciously allowed him to post ahead of its inclusion in the fourth edition of The C++ Programming Language.


It starts with The Basics. It was refreshing to see new features of C++11 introduced alongside the most rudimentary aspects of the language – rather than being viewed as a whole new language that teams might choose to adopt/ignore. I’m sure if you start learning C++ today, features such as enum class, auto, constexpr will seem natural, begging the question “What did you do without them?”.

I thought this code snippet was especially cute:

for (auto x : {10,21,32,43,54,65})
    std::cout << x << '\n';

I’m used to writing code in F# like this,

[| 10; 21; 32; 43; 54; 65 |] 
  |> Array.iter (fun i -> printf "%d\n" i)

but it’s great to see such concise code in C++ at well.

The second part concerns abstractions. This includes summaries of copy and move semantics. This note on move semantics is helpful because many explanations focus on how to move data into a new instance of a class rather than the state in which to leave the old object:

After a move, an object should be in a state that allows a destructor to be run. Typi- cally, we should also allow assignment to a moved-from object

Preventing copy and move:

Using the default copy or move for a class in a hierarchy is typically a disaster: Given only a pointer to a base, we simply don’t know what members the derived class has (§3.3.3), so we can’t know how to copy them. So, the best thing to do is usually to delete the default copy and move operations; that is, to eliminate to default definitions of those two operations

where C++11 provides the delete annotation to tell the compiler not to write a default copy/move operation, but you could follow today’s practice and declare it private and omit the implementation until your compiler catches up.

If you need to copy an object in a class hierarchy, write some kind of clone function. [Note that] a move operation is not implicitly generated for a class where the user has explicitly declared a destructor. Furthermore, the generation of copy operations are deprecated in this case. This can be a good reason to explicitly define a destructor even where the compiler would have implicitly provided one.

There are also useful examples of where to use type aliasing, for example this one that uses the assumption that STL containers provide a value_type alias (or typedef):

template<typename C>
using Element_type = typename C::value_type; 

template<typename Container> void algo(Container& c)
  Vector<Element_type<Container>> vec;
  // ... 

You can also use aliasing to define new templates by binding arguments on existing templates:

template<typename Value>
using String_map = Map<string,Value>;

String_map<int>m; //alias for Map<string,int>

Part three is about algorithms and containers.

The example for how to write operator>>(), read from, is particularly verbose – I’m sure it would have been better to show a regex solution alongside. Worth a look anyway for this mechanism for indicating a streaming failure (typically I would throw an exception):


Similarly, I hadn’t realised before that range-checked random access to a std::vector was possible via the at(size_t i) method:

T& operator[](int i) { return vector::at(i); } // range-checked

The final part is about concurrency and utilities.

One of the main utilities now available in C++11 is std::shared_ptr (which was sorely lacking from the previous standard).  However, Stroustrup hints that in many cases it’s sufficient to create an object on the stack with a local variable:

Unfortunately, overuse of new (and of pointers and references) seems to be an increasing problem.

When you do need to manage heap objects, std::unique_ptr is very lightweight with no space or time overhead compared to a built-in pointer.  You can pass or return unique_ptr’s in or out of functions, because the implementation uses move semantics (whereas std::shared_ptr is copied).

One concurrency topic that always causes problems is how to define a convention between locks so that deadlock cannot occur due to acquiring the locks in the wrong order.  There’s a neat example of how to avoid that:

// Initialise lock guards with their mutexes, but don't lock yet
std::lock_guard<std::mutex> lock1(mutex1, defer_lock);
std::lock_guard<std::mutex> lock2(mutex2, defer_lock);
std::lock_guard<std::mutex> lock3(mutex3, defer_lock);
// other preparation
std::lock( lock1, lock2, lock3 );
// Implicitly release all mutexes when locks go out of scope.

Stroustrup also introduces the concepts of futures and promises:

The important point about future and promise is that they enable a transfer of a value between two tasks without explicit use of a lock; “the system” implements the transfer efficiently.

The absence of locks is key and is also mentioned when introducing std::packaged_task and std::async.  This section might be better written in reverse, with the simpler async concept introduced first and locks/mutexes in context as the advanced technique.

Under <utilities>, a boon is likely to be std::tuple, a heterogenous sequence of elements (I’ve added the use of std::tie to show how to unpack the values):

auto myTuple = std::make_tuple(std::string("Hello"), 10, 1.23);
std::string a;
int b;
double c;
std::tie( a, b, c ) = myTuple;

I wouldn’t use std::tuple in an externally visible interface, but it’s useful to avoid defining types for passing multiple return values.

I like this example of using the new standard <random> library to simulate a die:

using my_engine = default_random_engine; // type of engine
using my_distribution = uniform_int_distribution<>; 
my_engine re {}; // the default engine
my_distribution one_to_six {1,6}; 
auto dice = bind(one_to_six,re); // make a generator
int x = dice(); // roll the dice: x becomes a value in [1:6]


Leave a comment

Filed under C++