Category Archive for C++

“Professional C++, 4th Edition” Released

It has been a lot of work, but I’m proud to announce my fourth edition of “Professional C++” 🙂
It is published by Wiley/Wrox.
And already available at Amazon.

Official Description

Get up to date quickly on the new changes coming with C++17

Professional C++ is the advanced manual for C++ programming. Designed to help experienced developers get more out of the latest release, this book skims over the basics and dives right in to exploiting the full capabilities of C++17. Each feature is explained by example, each including actual code snippets that you can plug into your own applications. Case studies include extensive, working code that has been tested on Windows and Linux, and the author’s expert tips, tricks, and workarounds can dramatically enhance your workflow. Even many experienced developers have never fully explored the boundaries of the language’s capabilities; this book reveals the advanced features you never knew about, and drills down to show you how to turn these features into real-world solutions.

The C++17 release includes changes that impact the way you work with C++; this new fourth edition covers them all, including nested namespaces, structured bindings, string_view, template argument deduction for constructors, parallel algorithms, generalized sum algorithms, Boyer-Moore string searching, string conversion primitives, a filesystem API, clamping values, optional values, the variant type, the any type, and more. Clear explanations and professional-level depth make this book an invaluable resource for any professional needing to get up to date quickly.

  • Maximize C++ capabilities with effective design solutions
  • Master little-known elements and learn what to avoid
  • Adopt new workarounds and testing/debugging best practices
  • Utilize real-world program segments in your own applications

C++ is notoriously complex, and whether you use it for gaming or business, maximizing its functionality means keeping up to date with the latest changes. Whether these changes enhance your work or make it harder depends on how well-versed you are in the newest C++ features. Professional C++ gets you up to date quickly, and provides the answers you need for everyday solutions.

Share

Next BeCPP UG Meeting Planned For February 28th, 2018

The next meeting of the Belgian C++ Users Group is planned for Wednesday February 28th, 2018 at 18:00 at Nokia.

Nokia ( http://nokia.be/ ) is sponsoring this event by providing the location, drinks and catering.

Nokia Logo

The agenda is as follows:

  • 18:00: Sandwiches.
  • 18:30: Session 1: Boost.Asio C++ (Network) Programming (Part 2) (Lieven de Cock)
    Boost.Asio is a cross-platform C++ library for network and low-level I/O programming, either using a synchronous or asynchronous model. We will examine this powerful library in 2 sessions.
    In this second session we will pick up where we left of, after connecting as a client we will start interacting with the server, and we will see how to implement a server application.
    We will do this both in a synchronous and an asynchronous way, keeping an eye on scalability.
    Note that the C++ Standard networking proposals are based directly on Boost.Asio, so next to learning this great library we are also preparing for the future C++ standard.
  • 19:30: Break
  • 19:45: Session 2: A possible future for embedded (Odin Holmes)
    Through the much-hyped advent of Industry 4.0 and IoT, billions of new bare metal devices will be connected to the internet or intranets and will be expected to talk to each other, even across company boundaries. This presents a plethora of new challenges, many of which share a common root; it is crucial that we build a foundation for code reuse and encapsulation of expertise in this domain. What does cross-platform code really mean when we are targeting thousands of ‘platforms’? When encapsulating expertise, we implicitly make assumptions about user code and user code implicitly makes assumptions about library code. What are valid assumptions? What is the basic interface? In this talk I will present a possible future for bare metal development which attempts to answer these questions.
  • 20:45: Introduction to Nokia, followed by a drink.

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

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

There are 60 seats available for this event.

Note: The deadline for registrations is February 25th, 2018!

Share

C++17: Initializers for if & switch statements

Two small, but very useful C++17 features are initializers for if and switch statements. These can be used to prevent polluting the enclosing scope with variables that should only be scoped to the if and switch statement. The for statement already supports such initializers since the beginning.
For example, suppose you are using a map to store the number of times a certain name occurs:

#include <cstddef>
#include <map>
#include <string>
#include <iostream>

int main()
{
    std::map<std::string, size_t> nameCounters{
        {"Marc", 5},
        {"Bob", 12},
        {"John", 3}
    };

    auto result = nameCounters.find("Bob");
    if (result != cend(nameCounters))
        std::cout << "Count: " << result->second << std::endl;
}

In this example I’m searching for a key in the map, and if the key is found, I output the associated value to the console. The result of calling find() is stored in result, but this variable is only used inside the if statement.
With C++17, you can initialize the result variable with an if statement initializer so that the result variable is only known inside the if statement and does not pollute the enclosing scope with unnecessary variables:

#include <cstddef>
#include <map>
#include <string>
#include <iostream>

int main()
{
    // ... Initialize map as before ...

    if (auto result = nameCounters.find("Bob"); result != cend(nameCounters))
        std::cout << "Count: " << result->second << std::endl;
}

Similar kind of initializers are supported for switch statements:

switch (<initializer>; <expression>) { /* ... */ }
Share

BeCPP Event January 9th, 2018

Barco has created a nice flyer for the Belgian C++ Users Group event of January 9th 2018.

Share

Next BeCPP UG Meeting Planned For January 9th, 2018

The next meeting of the Belgian C++ Users Group is planned for Tuesday January 9th, 2018 at 18:00 at Barco.

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

Barco Logo

The agenda is as follows:

  • 18:00: Sandwiches.
  • 18:30: Session 1: Threads are evil (Frederik Vannoote)
    Many applications beyond the scope of “Hello World” use threads for various reasons. Be it for having many sequential execution paths, preventing a blocked UI or offloading CPU intensive tasks to the background.
    However threads don’t come for free. They suddenly add a complex dimension to a simple application. Who dares to claim to have written a flawless threaded application? Is it really bringing a performance boost?
    Let’s have a closer look to what we are facing when using threads and what alternatives we have.
  • 19:00: Session 2: Legacy code refactoring case (Roeland Van Lembergen)
    Going from legacy C++ code to state of the art tested and testable code by means of focused refactoring and componentization. Building a future proof platform using code generation.
  • 19:30: Break
  • 19:45: Session 3: Boost.Asio C++ (Network) Programming (Lieven de Cock)
    Boost.Asio is a cross-platform C++ library for network and low-level I/O programming, either using a synchronous or asynchronous model. We will examine this powerful library in 2 sessions. The first session will first focus on using it as a task processor, something to offload work to, in a nice scaling way with respect to threads. Next we will have a look at timers based upon this library. Equipped with the basic techniques we will start looking at the networking part, first examining some structures and some first network activities, and if time permits it we will implement a first network client. From this talk on boos:asio:ioservice is ready to service you!
    In the second session we will dive head first in the network programming with no further limits.
    Note that the C++ Standard networking proposals are based directly on Boost.Asio, so next to learning this great library we are also preparing for the future C++ standard.
  • 20:45: Experience tour by Barco (Laserprojection/extreme surround sound in new cinema format, operation room for healthcare, control room, entertainment/concerts…), followed by a drink.

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

There are 100 seats available for this event.

Note: The deadline for registrations is January 5th, 2018!

Share

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