C++17: Inline Variables

Before C++17, if your class had any non-const static data members, you had to allocate memory for them. For example, suppose you have the following class definition:

class MyClass
{
private:
    static int s_anInt;
    static std::string s_aString;
};

Then your source file should contain the following:

int MyClass::s_anInt = 42;
std::string MyClass::s_aString = "Hello World!";

This is annoying.
C++17 now supports inline variables which allow you to write the MyClass definition as follows:

class MyClass
{
private:
    static inline int s_anInt = 42;
    static inline std::string s_aString = "Hello World!";
};

This feature makes it easier to write header only classes that contain non-const static data members.

At the time of this writing, Microsoft Visual C++ 2017 does not yet support inline variables.

Share

Implementing a Thread-Safe Singleton with C++11 Using Magic Statics

A couple of years ago I wrote a blogpost on how to write a thread-safe singleton using C++11. That implementation used std::call_once().

However, if your compiler is fully C++11 compliant, and by now, all major compilers are fully compliant, then the best way to implement a singleton is to use a magic static, as follows:

class CSingleton final
{
public:
	static CSingleton& GetInstance();

private:
	CSingleton() = default;
	~CSingleton() = default;

	CSingleton(const CSingleton&) = delete;
	CSingleton& operator=(const CSingleton&) = delete;
	CSingleton(CSingleton&&) = delete;
	CSingleton& operator=(CSingleton&&) = delete;
};

CSingleton& CSingleton::GetInstance()
{
	static CSingleton instance;
	return instance;
}

The most important change is the implementation of GetInstance() which now contains a local static variable (magic static). C++11 guarantees that this will be initialized in a thread-safe way.
I have now also marked the class as final, made the destructor non-virtual and private, and deleted the move constructor and move assignment operator.

Share

C++17: Direct vs Copy List Initialization

C++11 introduced the uniform initialization syntax using braced initializer lists. You have direct list initialization which does not include an equal sign, for example:

int myInt{42};

and you have copy list initialization which uses the equal sign, for example:

int myInt = {42};

The auto type deduction rules have changes in C++17. With C++17, if you use copy list initialization, then an initializer_list<> is deduced, for example:

auto initList1 = {42};
auto initList2 = {42, 84, 126};

All values in the braced initializer list must be of the same type. The following does not compile:

auto initList2 = {42, 84.42};

When you use direct list initialization, then a value is deduced. For example, the following deduces an int:

auto anInt{42};

This also means that the following causes a compilation error because more than 1 initialization value is given:

auto ints{42, 84, 126};

This is the new C++17 behavior. With C++11/C++14, all of the above would deduce to an initializer_list<int>.

This changed behavior is included since Microsoft Visual C++ 2015.

Share

C++17: Nested Namespaces

The second post in this series of C++17 features highlights a tiny but very useful new feature called nested namespaces.

Using multi-level namespaces in C++ has always been a pain. Suppose you are writing a game and you have a namespace called Core::Graphics::Rendering. Before C++17 you had to resort to something as follows

namespace Core {
    namespace Graphics {
        namespace Rendering {

            class PostProcessor
            {
            };

        }
    }
}

This leaves you with a very big indentation scheme. You could try to make it look a bit better as follows:

namespace Core { namespace Graphics { namespace Rendering {

    class PostProcessor
    {
    };

}}}

But this does not always plays nice with the auto formatting functionality of your IDE.

Say hello to C++17 nested namespaces. Now you can simply write the following:

namespace Core::Graphics::Rendering {

    class PostProcessor
    {
    };

}

Nested namespaces are supported in Microsoft Visual C++ 2015 since Update 3.

Share

C++17: Structured Bindings

This is a first post in a series of short articles on new C++17 features. These articles will not contain all little details of the new features being presented, but they give you an idea about what new functionality has been added to C++17.

This first article discusses structured bindings. They allow you to declare multiple variables with a single statement that are initialized with values from a pair, tuple, array, or even a struct.

Let’s look at an example using a tuple. Suppose you have the following tuple consisting of a double, string, and integer (note the use of the user-defined std::string literal s):

auto myTuple = std::make_tuple(1.1, "Hello"s, 42);

Before C++17, if you wanted to decompose this tuple into three separate variables, you could use tie() as follows:

double theDouble;
std::string theString;
int theInt;
std::tie(theDouble, theString, theInt) = myTuple;

That’s 4 lines of code just to decompose the tuple.

C++17 structured bindings allow you to do this with a single line:

auto[theDouble, theString, theInt] = myTuple;

It also works for pairs, and this comes in handy for example when using insert() to insert values into a map. insert() returns a pair with as first element an iterator to the inserted element, and as second element a Boolean that is true if the element was inserted successfully. You can decompose that pair as follows:

std::map<int, int> myMap{ {1, 11}, { 2,22 }, { 3,33 }};
auto[it, success] = myMap.insert({ 4,44 });

If you want to use a range-based for loop to iterate over the elements, you could do it as follows:

for (const auto& element : myMap) {
    std::cout << element.first << ": " << element.second << std::endl;
}

The type of the element variable is a pair containing the key and the value of the elements in the map.

Again, you can use structured bindings to make this shorter and easier to understand:

for (const auto&[key, value] : myMap) {
    std::cout << key << ": " << value << std::endl;
}

Structured bindings are available in Microsoft Visual C++ 2017 since Update 3.

Share

Visual Studio 2017 Released

Next BeCPP UG Meeting Planned For April 11th, 2017

The next meeting of the Belgian C++ Users Group is planned for Tuesday April 11th, 2017 at 18:00 at VUB.

SoftKinetic ( https://www.softkinetic.com/ ) is sponsoring this event by providing the location, drinks and catering.

SoftKinetic Logo
The agenda is as follows:

  • 18:00: Sandwiches.
  • 18:30: Session 1: Challenges in Modern Embedded Development Using C++ (Glyn Matthews)
    This talk will cover things such as constrained systems (e.g. CPU, cache, memory), older compilers affecting the use of library and language features from the 2011 standard and beyond, porting, testing etc. One theme will be that what’s “standard” and “modern” is not what you need to get your software working. In some ways, I’d like to push back a bit on the trend to more modern code bases, because it turns out it’s quite rare for developers to have access to the latest language features (and by “latest” I mean 6 years old…)
  • 19:30: Break
  • 19:45: Session 2: SFINAE and type traits: In the Mix (Lieven de Cock)
    The journey will start with a test drive of simple method overloading, shortly later enriched with some ‘templates’ laps. Then we shift gears and we add type traits to the mix. In order to arrive at the finish line, some SFINAE herbs are added to spice up the mix. And as the proof of the pudding is in the eating, a small use case, which will bring things together, will be served.
    In the end the main question remaining is: do we std::enable_if some drinks afterward?
  • 20:45: Short presentation and demo by SoftKinetic followed by a drink.

The event is free for everyone, but you need to register for it.

There are 50 seats available for this event.

Note: The deadline for registrations is April 4th, 2017!

Share

Next BeCPP UG Meeting Planned For January 24th, 2017

The next meeting of the Belgian C++ Users Group is planned for Tuesday January 24th, 2017 at 18:00 at Nobel Biocare.

Nobel Biocare ( https://www.nobelbiocare.com/ ) is sponsoring this event by providing the location, drinks and catering.

Nobel Biocare Logo
The agenda is as follows:

  • 18:00: Sandwiches.
  • 18:30: Session 1: What’s new in C++17, Part 2? (Peter Van Weert)
    This talk will continue the talk from November 2016, giving an overview of all the new features scheduled to be included in C++17. This second part will focus more on library changes.
  • 19:30: Break
  • 19:45: Session 2: Coming to terms with C++ in a huge financial application (Cosmin Cremarenco)
    Murex is a large financial application – ~15M lines of code of C/C++. Migrating from C to C++ has come with enormous challenges. Essential components had to be upgraded to what a C++ programmer naturally expects today. A legacy object framework based on C had to be deprecated in favour of C++, the build system had to be upgraded, proper testing put in place, processes devised to how third-party libraries are introduced in our codebase and used and, finally, a performant serialization system that is in-line with today’s expectations on latency and throughput when communicating between components written in different or same programming language.
  • 20:45: Short presentation/demo by Nobel Biocare followed by a drink.

The event is free for everyone, but you need to register for it.

There are 50 seats available for this event.

C++ Standard Library Quick Reference

We will be giving away a copy of C++ Standard Library Quick Reference.

Note: The deadline for registrations is January 20th, 2017!

Share

CppCon 2016 Videos Available Online


CppCon 2016 was again a great success. I’m looking forward to next year’s edition.
In the meantime, all sessions are now available on the CppCon YouTube video channel.
Enjoy all the material 🙂

Share

Next BeCPP UG Meeting Planned For November 24th, 2016

The next meeting of the Belgian C++ Users Group is planned for Thursday November 24th, 2016 at 18:00 at Nikon Metrology HQ.

Nikon Metrology ( http://nikonmetrology.com/ ) is sponsoring this event by providing the location, drinks and catering.

Nikon Metrology Logo

The agenda is as follows:

  • 18:00: Sandwiches.
  • 18:30: Session 1: What’s new in C++17? (Peter Van Weert)
    This talk will give an overview of all the new features scheduled to be included in C++17.
  • 19:30: Break
  • 19:45: Session 2: Mobile App Development for Multiple Platforms with Visual C++, 2016 (Marc Gregoire)
    Visual C++ supports mobile app development for Windows, Android, and iOS from a single code base, optionally with a thin platform-specific UI layer. The resulting binaries can be deployed to an emulator or to a real device and debugged on both, all from within Visual C++. This presentation is a follow up of my previous BeCPP presentation, and as such the session will only briefly cover the basics of cross-platform mobile app development. Please view https://www.youtube.com/watch?v=2Y47g8xNE1o or https://channel9.msdn.com/events/CPP/CppCon-2015/CPPConD02V019 for this material in depth. In this follow up, we go over the new features added for cross-platform development since last year. Additionally, we continue where last year’s session ended, and will go deeper on how to write your applications to have a native look-and-feel UI on each of the different platforms.
  • 20:45: Short presentation and guided tour of Nikon Metrology followed by a drink.

The event is free for everyone, but you need to register for it.

There are 50 seats available for this event.

C++ Standard Library Quick Reference

We will be giving away a copy of C++ Standard Library Quick Reference.

Note: The deadline for registrations is November 20th, 2016!

Share

Slides of my CppCon 2016 Presentation “Mobile App Development for Multiple Platforms with Visual C++, 2016″

On September 22th, 2016 I gave a presentation titled “Mobile App Development for Multiple Platforms with Visual C++, 2016” at CppCon 2016.
The slides of my presentation can be downloaded below:


Looking forward to next year’s edition of CppCon, which has been announced to be on September 25th-29th in Bellevue, Washington 🙂

Share

Performance Improvements with Visual Studio 2015 Update 2

Visual Studio 2015 Update 2, released on March 30 2016, brought a couple of performance improvements.

  • Enabled a new database engine; now, C++ Project load should be faster and experience fewer UI delays.
  • Increased the speed of extracting floating-point numbers with iostreams (in other words, “stream >> dbl”). It’s now up to 19x faster, and all bits of the extracted value are now correct.
  • Increased the speed of std::vector reallocation and std::copy(); they are up to 9x faster as they call memmove() for trivially copyable types (including user-defined types).
  • Increased the speed of std::vector, which is up to 11x faster.
  • Increased the speed of std::string::replace(), which is enormously faster when replacing same-size substrings.
  • Increased the speed of std::string::push_back(), which is up to 3x faster.
  • Increased the speed of std::sub_match comparisons, as they now avoid constructing temporary std::strings.
  • Increased the speed of std::function’s copy constructor; it is slightly faster with a reduced codegen size.

The full official release notes can be found here.

Share

New Book “C++ Standard Library Quick Reference” Now Available


My brand new book “C++ Standard Library Quick Reference” co-authored with Peter Van Weert and published by Apress is now available:

Here is the abstract:

This quick reference is a condensed reference guide to the essential data structures, algorithms, and functions provided by the C++ Standard Library. Used by millions of C++ programmers on a daily basis, the C++ Standard Library features core classes for strings, I/O streams, and various generic containers, as well as a comprehensive set of algorithms to manipulate them. In recent years, the C++11 and C++14 standards have added even more efficient container classes, a new powerful regular expression library, and a portable multithreading library featuring threads, mutexes, condition variables, and atomic variables.

Needless to say, it is hard to know and remember all the possibilities, details, and intricacies of this vast and growing library. This handy reference guide is therefore indispensable to any C++ programmer. It offers a condensed, well-structured summary of all essential aspects of the C++ Standard Library. No page-long, repetitive examples or obscure, rarely used features. Instead, everything you need to know and watch out for in practice is outlined in a compact, to-the-point style, interspersed with practical tips and well-chosen, clarifying examples. The book does not explain the C++ language or syntax, but is accessible to anyone with basic C++ knowledge or programming experience. Even the most experienced C++ programmer though will learn a thing or two from it and find it a useful memory-aid. Among the topics covered are:

  • The essentials that the C++ Standard Library has to offer
  • How to use containers to efficiently store and retrieve your data
  • How to use algorithms to inspect and manipulate your data
  • How lambda expressions allow for elegant use of algorithms
  • What the standard string class provides and how to use it
  • How to write localized applications
  • What functionality the library provides for file and stream-based I/O
  • What smart pointers are and how to use them to prevent memory leaks
  • How to write safe and efficient multi-threaded code using the C++11 threading libraries
Share

Next BeCPP UG Meeting Planned For June 30th, 2016

NOTE: Due to a logistics problem, the date has changed. The event will now take place on Thursday June 30th and not on June 23rd!

The next meeting of the Belgian C++ Users Group is planned for Thursday June 30th, 2016 at 18:00 at Newtec.

Newtec ( http://www.newtec.eu/ ) is sponsoring this event by providing the location, drinks and catering.

Newtec

The agenda is as follows:

  • 18:00: Sandwiches.
  • 18:30: Session 1: Build a database-independent cross-platform persistence layer with Qt (Johan Decorte) Most applications need some kind of persistence. Often relatonal databases are a good choice to store and retrieve data. Besides a cross-platform IDE Qt also provides extensive general-purpose libraries including a database-independent, object-oriented and clean SQL Module API. You can decide even at runtime wether your target database is e.g. Oracle, MS SQL Server or mySQL. Both plain SQL and stored procedure calls are supported.
  • 19:30: Break
  • 19:45: Session 2: Objects? No Thanks! (Wouter van Ooijen) Micro-controller programming can benefit from compile-time polymorphism without paying a run-time price by using static class templates. For small micro-controllers (kilobytes of memory) C++ run-time polymorphism (using objects and virtual methods) is often deemed too expensive in ROM, RAM, and run-time overhead. This talk shows how templates can be used to implement compile-time polymorphism, and static classes to avoid the need for run-time objects. This technique can produce highly modular and composable code that is still as efficient as dedicated C code, but offers better prospects for re-use. This approach is illustrated with an abstraction for GPIO (General Purpose Input Output) pins and ports, with an implementation on an LPC1114 microcontroller, and a number of decorators for pins and numbers.
  • 20:45: Short presentation and guided tour by Newtec.
  • 21:00: Drink

The event is free for everyone, but you need to register for it.

There are 50 seats available for this event.

Professional C++, 3rd Edition

We will be giving away a copy of Professional C++, 3rd Edition.

Note: The deadline for registrations is June 27th, 2016!

Share

Slides GDG Presentation Cross-Platform Mobile App Dev with VC++

GDG-program-logo
 

On Tuesday 15th of March I gave a presentation for the GDG Brussels (Google Developer Group) in Belgium titled “Cross-Platform Mobile App Development with Visual C++ 2015”. Below you can download the slides.

 

Marc Gregoire - GDG - Cross-Platform Mobile App Development with Visual C++ 2015

Share

Milestone: VS 2015 Update 2’s Standard Library is C++11, C++14, and C++17-so-far Feature Complete

The C++ Standard Library in the Visual Studio 2015 Update 2 release is C++11, C++14, and C++17-so-far feature complete. This includes all features from C++17 that are currently in that standard proposal: SFINAE-friendly result_of, improvements to pair and tuple, shared_mutex, removal of deprecated iostreams aliases, variable templates for type traits (is_same_v, …), as_const(), logical operator type traits (conjunction, …), owner_less<>, variadic lock_guard, and additions to <chrono>: floor(), ceil(), round(), and abs().
More information, including a detailed list can be found here.

Share

Videos are online of the Windows 10 Dev Day Belgium

The Windows 10 Developer Day brought together more than 300 developers across 3 locations in Belgium (Brussels, Hasselt and Gent). The sessions in Hasselt were recorded and are now available online.

Dive into the benefits that come with the Universal Windows Platform and learn how to have your app run on any device regardless of screen size.

Be amazed about the ease of making the web work for you on Windows 10. Get to know the advantages of building a cloud-connected, mobile experience and see for yourself what the future computing looks like!

Watch the videos on Channel 9.

Share

Next BeCPP UG Meeting Planned For December 3th, 2015

The next meeting of the Belgian C++ Users Group is planned for Thursday December 3th, 2015 at 18:00 at Selligent.

Selligent ( https://www.selligent.com/ ) is sponsoring this event by providing the location, drinks and catering.

OM Partners

The agenda is as follows:

  • 18:00: Sandwiches.
  • 18:30: Session 1: Move semantics && rvalue references, part 2 (Bert Rodiers) In this presentation we will continue where we left off a year ago. First we will discuss some alternative implementations for the move operators and briefly talk about how to pass arguments. The rest of the talk dives into rvalue references in combination with deduced types and perfect forwarding.
  • 19:30: Break
  • 19:45: Session 2: Cross-Platform Mobile App Development with Visual C++ 2015 (Marc Gregoire) Visual C++ 2015 supports the development of apps for the Windows platform as well as for Android and iOS. A single code base, possibly with a thin platform-specific UI layer, can be compiled to run on Windows, Android, and iOS. The resulting binary can be published to a device and debugged, all from within Visual C++ 2015. This presentation introduces you to such cross-platform mobile app development, including debugging and emulation, and includes a number of demos.
  • 20:45: Short presentation by Selligent.
  • 21:00: Drink

The event is free for everyone, but you need to register for it.

There are 50 seats available for this event.

Professional C++, 3rd Edition

We will be giving away 2 copies of Professional C++, 3rd Edition.

Note: The deadline for registrations is November 27th, 2015!

Share

Slides of my CppCon 2015 Presentation “Cross Platform Mobile App Development in VC++2015”

On September 22th, 2015 together with Ankit Asthana from Microsoft I gave a presentation titled “Cross-Platform Mobile App Development with Visual C++ 2015” at CppCon 2015.
The slides of our presentation can be downloaded below:


Looking forward to next year’s edition of CppCon 🙂

Share

CppCon 2015 Program


The CppCon 2015 program is almost complete. The program contains over 100 one-hour sessions by over 80 speakers. This year, the opening keynote will be given by C++ creator Bjarne Stroustrup on Writing Good C++14.

I’ll be giving a presentation myself titled “Cross-Platform Mobile App Development with Visual C++ 2015” on Tuesday, September 22 (3:15pm – 4:15pm).

Share