Modern C++ Tips and Tools

C++ allows you to write clean, safe and fast code, and writing it is even easier than ever thanks to new features in C++11 and C++14. This article highlights a couple of tips.

Comments & ‘Cleverness’

Code gets read a lot more often than it gets written, so make sure that your code can be read and understood in the future, by yourself and by other developers. This means that you have to add comments, and that you should avoid trying to make code as terse and ‘clever’ as possible; because that hurts readability.

Memory Management

In modern C++ you should avoid any explicit calls to delete operators or functions to deallocate memory such as free(). Code that relies on such explicit calls is susceptible to memory leaks. For example:

void foo(size_t size) {
    char* buffer = new char[size];
    // ...
    delete [] buffer;
}

The code is straightforward; it allocates memory, does something with the memory, and then deletes the memory. It uses a ‘naked’ pointer, which you have to manage yourself. This piece of code causes a memory leak if an exception is thrown before the delete operator is called. You should avoid using naked pointers, instead use encapsulation objects that automatically handle the memory. For example, the above code should be written using a container such as a vector:

void foo(size_t size) {
    std::vector buffer(size);
    // ...
}

Using a container, there is no need to free the memory, the destructor of the container will handle all that for you. Similarly, if you need dynamically allocated objects, do not store them in naked pointers, instead use smart pointers such as std::unique_ptr, which is not reference counted, or if you need shared ownership, std::shared_ptr, which is reference counted. unique_ptr will automatically delete the object when the unique_ptr goes out of scope. An object wrapped in a shared_ptr is automatically deleted when the reference count goes to zero.

When you use unique_ptr, use std::make_unique<>(). Similarly, use std::make_shared<>() when you use shared_ptr.

One key point to remember: never use std::auto_ptr, it has officially been deprecated because of its problems. One of its problems is that it is forbidden to store them in STL containers because auto_ptr does not meet C++98/03’s requirements for container elements.  unique_ptr  and shared_ptr don’t have any of these problems and are perfectly safe to use in STL containers.

The auto Keyword

Use auto to let the compiler deduce the type of variables automatically. This helps a lot with complicated types that are hard or even impossible to write. For example:

std::map<std::string, std::vector> myMap;
for (std::map<std::string, std::vector>::iterator iter = begin(myMap);
     iter != end(myMap); ++iter)
{
    //...
}

This is complicated, difficult to write and error prone.
Note that since C++11 it’s recommended to use the non-member functions std::begin(), end(), cbegin(), cend(), rbegin(), rend(), crbegin(), and crend() instead of the member functions.
Using the auto keyword the above can be rewritten in a very clean way:

for (auto iter = begin(myMap); iter != end(myMap); ++iter) { ... }

Using the range-based for loop, the code can be written even more elegantly:

for (auto&& item : myMap) { ... }

Or:

for (auto& item : myMap) { ... }

Or:

for (const auto& item : myMap) { ... }

Never write the following, unless your container only contains primitive types:

for (auto item : myMap) { ... }

If you use this for containers with non-primitive elements performance will suffer because item will be a copy of each of the elements in the container.

nullptr

Do not use NULL for pointers, use the nullptr keyword. NULL is a macro for 0 which can sometimes result in problems that are hard to track down. nullptr is really a null pointer type and is not just a macro for 0.

Move Semantics

Move semantics since C++11 helps with performance, allowing objects to be moved instead of copied. It is based on rvalue references, represented as &&. C++ automatically uses move semantics in cases where the source object will cease to exist. You can explicitly move an object by using std::move(). The STL also supports move semantics. To add move semantics to your classes you only need to implement a move constructor and move assignment operator which have the following prototype:

MyObject(MyObject&& src);               // Move constructor
MyObject& operator=(MyObject&& rhs);    // Move assignment operator

Lambda Expressions

Lambda expressions are a powerful addition to the C++ language. One huge benefit is that they make it much easier to use STL algorithms. For example, you can use the count_if() algorithm in combination with a simple lambda expression to count all elements in a vector that are less than 0.

std::vector vec;
auto count = std::count_if(cbegin(vec), cend(vec),
    [](int i){ return i < 0; });

Investing time in learning about lambda expressions will pay itself off quickly.

Threading

You should read up on the threading functionalities introduced in C++11. One useful and often overlooked function is std::call_once(), used to make sure that a specific callable entity is executed exactly one time, no matter how many threads call it simultaneously. This can for example be used to make a compact and thread safe implementation of the singleton pattern.

Strings

Text matching, parsing, and searching can be tricky and complicated, especially when it should work with Unicode strings. You should avoid writing your own functions to perform such operations, instead use classes from <regex> such as std::wregex.

C++11 supports raw string literals. They are extremely useful in the context of regular expressions. For example, the following regular expression searches for spaces, newlines, and backslashes:

string s = "( |\\n|\\\\)";

The last 4 backslashes are correct. If you want to match a backslash, it needs to be escaped in the regular expression, thus \\. If you want to write \\ in a normal string literal, you need to escape both backslashes, resulting in 4 of them. Using raw string literals you simply write:

string s = R"(( |\n|\\))";

R”( and )” denote the boundary of the raw string literal.

Random Numbers

If your application needs to generate random numbers, don’t use the old C style srand()/rand() functions. Their randomness is not good. Instead, use <random>, which contains classes to generate random numbers, such as a Mersenne Twister, and supports different mathematical distributions, for example a uniform distribution, a Poisson distribution, and so on.

Further Reading

Take a look at “Professional C++ 2nd Edition” if you are determined to master C++, including all C++11 features.

Share

Happy New Year 2014

2014
Happy New Year
Sretna Nova Godina
Gelukkig Nieuwjaar
Bonne Année
🙂

Share

MVP Global Summit 2013 November Report

I gave a report of the November MVP Global Summit 2013 to software engineers in my company. Obviously, I’m only talking about things that did not fall under NDA.
The slides can be downloaded below:

Share

Announcing the Visual C++ Compiler November 2013 CTP

Visual Studio 2013 has only been released very recently, and the Visual C++ team already has a new CTP out with new features 🙂
The following table gives an overview and even includes features that are planned for future releases.

  • Implicit move special member function generation (thus also completing =default)
  • Reference qualifiers on member functions (a.k.a. “& and && for *this”)
  • Thread-safe function local static initialization (a.k.a. “magic statics”)
  • Inheriting constructors
  • alignof/alignas
  • __func__
  • Extended sizeof
  • constexpr (except for constructors)
  • noexcept (unconditional)
  • C++14 decltype(auto)
  • C++14 auto function return type deduction
  • C++14 generic lambdas (with explicit lambda capture list)
  • (Proposed for C++17) Resumable functions and await

Remember, this is a CTP so it does not come with a Go Live license.
More details can be found on the VCBlog.

Share

Meeting C++ 2013 – “Introduction to Microsoft C++ AMP”

The 2013 edition of Meeting C++ was once again a great conference.
This year I gave an introduction to Microsoft C++ AMP on the conference.
The session was a great success. I estimate there were around 100 people in the room, and lots of interesting questions 🙂
After the session I read on Twitter

Awesome presentation on C++ AMP in track B. #meetingcpp

C++ AMP makes it possible to write C++ for GPUs in a STLesque fashion. #meetingcpp

Below you can download the slides of my presentation.

Share

MVP Global Summit November 2013

Looking forward to the Microsoft MVP Global Summit November 2013 🙂
MVP Global Summit November 2013

Share

Visual Studio 2013 Available for Download

The final versions of Visual Studio 2013, Team Foundation Server 2013 and .NET 4.51 are now available from MSDN. You can also download trials.

VS 2013 can be installed side by side with previous versions of Visual Studio or, if you have a VS 2013 pre-release, it can be installed straight on top of the pre-release. TFS 2013 cannot be installed side by side but can also be installed on top of either a previous version (TFS 2012 or TFS 2010) or a pre-release.

Learn more about what’s new in Visual Studio 2013.

What’s new in Visual C++ 2013 (excerpt from MSDN):

  • Compiler
    • Added support for the following ISO C++11 language features:
      • Default template arguments for function templates.
      • Delegating constructors.
      • Explicit conversion operators.
      • Initializer lists and uniform initialization.
      • Raw string literals.
      • Variadic templates.
      • Alias templates.
      • Deleted functions.
      • Non-static data member initializers (NSDMIs).
      • Defaulted functions.  (using =default to request memberwise move constructors and move assignment operators is not supported)
    • Added support for the following ISO C99 language features:
      • _Bool
      • Compound literals.
      • Designated initializers.
      • Mixing declarations with code.
    • String literal conversion to modifiable values can be disallowed by using the new compiler option /Zc:strictStrings. In C++98, conversion from string literals to char * (and wide string literals to wchar_t *) was deprecated. In C++11, the conversion was removed entirely. Although the compiler could strictly conform to the standard, instead it provides the /Zc:strictStrings option so that you can control conversion. By default, the option is off. Note that when you are using this option in debug mode, the STL will not compile.
    • rvalue/lvalue Reference Casts. With rvalue references, C++11 can clearly distinguish between lvalues and rvalues. Previously, the Visual C++ compiler did not provide this in specific casting scenarios. A new compiler option, /Zc:rvalueCast, has been added to make the compiler conformant with the C++ Language Working Paper(see section 5.4, [expr.cast]/1). The default behavior when this option is not specified is the same as in Visual Studio 2012.
  • STL
    • Support for the C++11 explicit conversion operators, initializer lists, scoped enums, and variadic templates.
    • All containers now support the C++11 fine-grained element requirements.
    • Support for these C++14 features:
      • “Transparent operator functors” less<>, greater<>, plus<>, multiplies<>, and so on.
      • make_unique<T>(args…) and make_unique<T[]>(n)
      • cbegin()/cend(), rbegin()/rend(), and crbegin()/crend() non-member functions.
    • <atomic> received numerous performance enhancements.
    • <type_traits> received major stabilization and code fixes.

This list is just a small part of everything that’s new. There are also

  • Visual C++ library enhancements
  • C++ application performance enhancements
  • Diagnostics enhancements
  • 3D graphics enhancements
  • Quite a few very nice IDE and Productivity enhancements.

Read all the details here.

Visual C++ 2013 now also supports “just my code” debugging which makes working with C++ even better. The ability to filter the call stack down to just the code you wrote when debugging has long existed for managed languages and is now available for C++ 🙂

Share

Next BeCPP UG Meeting Planned For November 4th, 2013

The next meeting of the Belgian C++ Users Group is planned for Monday November 4th, 2013 at 18:00 at LMS International, a Siemens Business.

LMS International ( http://www.lmsintl.com/ ) is sponsoring this event by providing the location, drinks and catering.

LMS International

This time, there will be one speaker, giving two presentations of one hour on one subject. The agenda is as follows:

  • 18:00: Sandwiches.
  • 18:30: Session 1: Strings and String Manipulation in C++, Part 1 (Lieven de Cock) Once there were c-arrays, evolution brought us std::string. This made life easier, and less manual reimplementation was needed because of the power std::string brought to the table. Nevertheless we still keep on reimplementing basic and advanced string manipulation functionality. By this continuously reinventing the wheel we spend a lot of time fixing the same mistakes, while out there are tried and tested and proven libraries. C++11 also brings more power, but we will focus on boost string manipulations. Basic manipulations, like replace, find, erase, split, join, trim, …, next to lexical_cast, boost tokenizer, regex (both boost and std) will be explained and show cased. Next to the lexical_cast we will mention std::to_string. Similar library functionality provided by the POCO libraries will be shown too. String power is at your fingers for free, just say the magic word.
  • 19:30: Break
  • 19:45: Session 2: Strings and String Manipulation in C++, Part 2 (Lieven de Cock)
  • 20:45: Demo of an LMS International software product followed by a drink.

Read the official announcement.

Register for this free event.

Share

Visual Studio 2013 UI Changes

The Visual Studio 2013 Preview has a number of UI improvements compared to 2012.
There is again a bit more color in the IDE, and borders between controls and windows are more visible.
Below is an example of the Solution Explorer

Read this blog post on the Visual Studio team blog for more details.

Share

My Article “Advanced C++ Tips and Tools” on Amazon

My article “Advanced C++ Tips and Tools” is live on the tech.book(store) website of Amazon.

C++ allows you to write clean, safe and fast code, and writing it is even easier than ever thanks to new features in C++11. This article highlights a couple of tips…

You can read the full article here.

Share

Next BeCPP UG Meeting Planned For June 12th, 2013

The next meeting of the Belgian C++ Users Group is planned for Wednesday June 12th, 2013 at 18:00 at Nikon Metrology HQ.

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

There will be two international speakers:

  • Joel Falcou is an assistant professor at the University Paris-Sud and researcher at the Laboratoire de Recherche d’Informatique in Orsay, France. His work focuses on investigating high-level programming models for parallel architectures (present and future) and providing efficient implementation of such models using high-performance language features. He’s an active member of the Boost community and CEO of MetaScale, a French start-up valorizing his research. He is also a member of the ISO C++ Standards Committee.
  • Jens Weller is a self-employed C++ specialist, working with C++ for over 14 years. He is organizing the C++ conference “Meeting C++” in Düsseldorf, and also runs http://meetingcpp.com. Jens has some vast C++ experience gathered as a freelancer in the IT Industry.

The agenda is as follows:

  • 18:00: Sandwiches.
  • 18:30: Session 1: Qt5 – Multimedia Overview (Jens Weller) The talk will give a short introduction into Qt5, and focus on its Multimedia Framework, showing how to write an MP3 Player or a video recorder in Qt5.
  • 19:30: Break
  • 19:45: Session 2: Boost.Proto (Joel Falcou) C++ Embedded Domain Specific Languages Made Easy.
  • 20:45: Guided tour of Nikon Metrology followed by a drink.

Read the official announcement.

Register for this free event.

Share

Community Day 2013

The Belgian community is organizing the 7th edition of Community Day! Community Day 2013 will take place on June 20th 2013 in Utopolis Mechelen.

14 user groups will outperform themselves to bring you their view on Microsoft products in more than 25 sessions. 2013 is not a release year for Microsoft so far, so that gives us, the community, the opportunity to do deep-dive sessions in interesting topics. The biggest goal of this edition is bringing you high-quality sessions. And we’re pretty sure we have achieved that. Why don’t you take a look yourself at our agenda? Oh and don’t forget to take a look at our sponsor page, because it’s thanks to them we can organize this great event!

Convinced you need to be part of the experience again? Want to register? Great! Registration opens in the second week of May so come back soon to reserve your seat. Remember that last year, the event was sold out very fast, so make sure you’re on time!

The Microsoft Community Day 2013 is powered by:

  • AZUG
  • Belgian C++ user group
  • BIWUG
  • CLUG
  • Pro-Exchange
  • SCUG
  • SQLUG
  • ACCB.net/VBIB
  • Visug
  • WinSec
  • WinTalks
  • DotNetHub
  • MADN
  • TechNine

We hope to see you on June 20th!

Share

Join the Belgian Windows 8 apps race

And win prices 🙂

Share

Microsoft MVP VC++ 2013 Award

I got the confirmation email from Microsoft that my MVP (Most Valuable Professional) award for Visual C++ is extended for 2013 🙂
I’m already looking forward to the next Summit 🙂

Congratulations! We are pleased to present you with the 2013 Microsoft® MVP Award! This award is given to exceptional technical community leaders who actively share their high quality, real world expertise with others. We appreciate your outstanding contributions in Visual C++ technical communities during the past year.

See my MVP profile.

Share

Visual Studio 2012 Update 2 Now Available

Microsoft has released Update 2 for Visual Studio 2012 (VS2012.2). You can get it here.

Just as with VS2012.1 (which is installed as part of VS2012.2 for those of you who don’t already have VS2012.1 installed), this release contains important fixes as well as a wealth of new functionality, addressing feedback we’ve received from the community and aligning with key software development trends in the market. The new functionality primarily spans (though is not limited to) five areas of investment: agile planning, quality enablement, Windows Store development, line-of-business development, and the general developer experience.

Check out Somasegar’s blog post for more details on this update.

Share

MVP Global Summit 2013 February Report

On March 25th, I gave a report of the February MVP Global Summit 2013 to software engineers in my company. Obviously, I’m only talking about things that did not fall under NDA.
The slides can be downloaded below:

Share

Meeting C++ 2013 Announcement

After last years great success, there will be a Meeting C++ 2013 with 2 days full of C++ in Germany this Fall. Meeting C++ 2013 will be again at the 2nd weekend of November (8/9.11.2013). This time the conference will take place at the Lindner Congresshotel in Düsseldorf. For this year there will be 25 talks and up to 2 keynotes for the 250 attendees at the conference!

Like last year, this event is organized independently, covering most its costs over the ticket price. There will be 3 tracks about C++ this year, with the 3rd track being a theme track about C++ and UI. Talks about Qt5, XAML, wxWidgets, GTK, Apps and QML could take place in this theme track. The other two tracks will offer general C++ talks like last year. Meeting C++ 2013 is looking again for sponsors, with sponsors from last year already being contacted.

The call for papers for Meeting C++ 2013 has started and will end on May 15th. The process will be a bit different then last years. Talks will be collected, and then anonymously rated by a Program Committee consisting out of community members, organizers and sponsors. All ratings will be combined and used to do the final placement in the schedule. Speakers will have the opportunity to publish an entry about their talk at our blog this year! Tickets will be available soon, starting with the early bird ticket sale. This year there will be 250 tickets available for the conference, early bird tickets will cost €399, normal tickets €499. Early bird tickets will be sold till the end of June, after the schedule is available for one month, or till the 100 available tickets are sold out.

Share

Superhackathon in Belgium

banner_superhackathon_180x150Microsoft is organizing a Superhackathon in Belgium on 27th of March. Starting at 9AM for the Day part, and continuing until midnight for the Night part. This is a hackathon organized simultaneously in Brussels, Genk, Mons, and Kortijk.

Code, build, eat, drink & win.

Experts will be on site to help you with the last phase of building your first Windows 8 or Windows Phone 8 application. The event will be streaming live everywhere to the world.

There will be experts (many!), breakfast, pizza, coffee (lots!) and Red Bull. You can win prizes and rewards such as tickets to TechEd, Asus Vivo Tab, Lumia Phone and more.

Read more and register.

Share

Boost.Asio C++ Network Programming


I recently finished reading “Boost.Asio C++ Network Programming” written by John Torjo and published by Packt Publishing. Information given by the publisher:

Overview:

  • Augment your C++ network programming using Boost.Asio
  • Discover how Boost.Asio handles synchronous and asynchronous programming models
  • Practical examples of client/server applications
  • Learn how to deal with threading when writing network applications
  • Harness the power of Boost with plenty of examples that you can build upon

What you will learn from this book:

  • How to easily reference Boost.Asio programming
  • Synchronous versus asynchronous using Boost.Asio
  • How threading affects programming using Boost.Asio
  • Create your own echo client and server
  • More examples of client/server applications, both synchronous and asynchronous
  • Implement your own asynchronous operations
  • Co-routines: asynchronous operations with a synchronous feel
  • Use Boost.Asio for SSL Networking
  • Debug Boost.Asio
  • Use Boost.Asio for more than just networking

I love the Boost libraries, and I’m interested in network programming, so I decided to read this book. The book has a hands-on approach with a couple of sample programs. What I like is that these sample programs have been structured in such a way so they can be reused for your own projects. They are like skeleton examples, and all source code can be downloaded from the book’s website.

The book does not cover any real networking theory. For example don’t expect an in-depth discussion of how the TCP, UDP, or ICMP protocols work; that’s not the goal of this book. The goal is to show, with practical examples, how to use the Boost.Asio networking library.

While reading chapter 1, my initial reaction to the contents was rather negative. Chapter 1 is a bit convoluted, not so easy to understand, and even has a couple of errors in it. However, subsequent chapters are structured more logically and are understandable, though sometimes a discussion accompanying a piece of code can be a bit brief.

As an introduction to the library, Chapter 3 shows a basic Echo client/server example which is quite good. There is a synchronous and asynchronous TCP implementation of the client and server, and also a synchronous UDP implementation of the client and server. Subsequent chapters implement more useful client/server applications.

The book is not your one-stop destination for everything related to the Boost.Asio library, but it’s a great introduction to get you started with the library, to get to know the terminology used in the library, to learn about the difference between synchronous and asynchronous programming, to learn how to use multi-threading using the Boost threading library, and to get nice skeleton applications that you can reuse in your own projects. Several skeleton applications are provided such as synchronous and asynchronous versions, and single-threaded and multi-threaded versions.

Share

The C++ REST SDK (“Casablanca”)

The C++ REST SDK (codename “Casablanca”) has officially been released as an open source project on CodePlex (http://casablanca.codeplex.com). It includes tools to quickly write modern, asynchronous C++ code that connects with REST services.

It makes it much more easy to write application in C++ that use networking. Here is a simple example that uploads a file to an HTTP Server:

#include <http_client.h>
#include <filestream.h>
#include <uri.h>
#include <thread>

#pragma comment(lib, "casablanca110")

using namespace concurrency::streams;
using namespace web::http::client;
using namespace web::http;
 
int main()
{
  // Open stream to file.
  file_stream<unsigned char>::open_istream(L"ReadMe.txt").then([](basic_istream<unsigned char> fileStream)
  {
    // Make HTTP request with the file stream as the body.
	http_client client(U("http://www.myhttpserver.com"));
    client.request(methods::PUT, L"myfile", fileStream).then([fileStream](http_response response)
    {
      fileStream.close();
      // Perform actions here to inspect the HTTP response...
      if (response.status_code() == status_codes::OK)
      {
      }
    });
  });
  std::this_thread::sleep_for(std::chrono::seconds(10));
  return 0;
}

The library also makes it easy to create and consume JSON formatted strings from C++.
Checkout this blog post for a little bit more details.

Share