Category Archive for Software Development

“Professional C++, 6th Edition” Released

I’m proud to announce that the new edition of my book “Professional C++, 6th Edition” is finished 🙂
It has been updated to the C++23 standard and uses certain C++23 features throughout all examples.

It is published by Wiley/Wrox, and available on Amazon.

Official Description

Expand your C++ knowledge quickly and efficiently with this advanced resource

In the newly revised sixth edition of Professional C++, veteran software engineer and developer Marc Gregoire delivers yet another volume that raises the bar for advanced programming manuals. Covering almost all features of the new C++ standard codenamed C++23, the book offers case studies with working code that’s been tested on Windows and Linux.

As the leading resource for dedicated and knowledgeable professionals seeking to advance their C++ skills, this book provides resources that help readers:

  • Master new features of the latest standard, C++23
  • Maximize C++ capabilities with effective design solutions
  • Discover little-known elements and learn about pitfalls and what practices to avoid
  • Grasp testing and debugging best practices
  • Learn about tips and tricks for efficiency and performance

C++ is a complex language. Professional C++, 6th Edition, allows dedicated practitioners to remain current and abreast of the latest developments and advances.

Share

“Professional C++, 5th Edition” Released

After working on it for a year, I’m proud to announce my new book “Professional C++, 5th Edition” is finished 🙂

It has been updated to the C++20 standard and uses certain C++20 features, such as modules and std::format(), throughout all examples.

It is published by Wiley/Wrox, and available on Amazon.

Official Description

Improve your existing C++ competencies quickly and efficiently with this advanced volume

Professional C++, 5th Edition raises the bar for advanced programming manuals. Complete with a comprehensive overview of the new capabilities of C++20, each feature of the newly updated programming language is explained in detail and with examples. Case studies that include extensive, working code round out the already impressive educational material found within. 

Without a doubt, the new 5th Edition of Professional C++ is the leading resource for dedicated and knowledgeable professionals who desire to advance their skills and improve their abilities. This book contains resources to help readers: 

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

Notoriously complex and unforgiving, C++ requires its practitioners to remain abreast of the latest developments and advancements. Professional C++, 5th Edition ensures that its readers will do just that. 

Share

“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

Visual Studio 2017 Released

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

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

C++14 STL Features, Fixes, And Breaking Changes In Visual Studio 14 CTP1

Stephan T. Lavavej, aka STL, has written a very detailed blog post describing new C++14 STL features, implemented fixes, and breaking changes in Visual Studio 14 CTP1. Read it here.

One notable breaking change is that containers cannot have const elements:

The Standard has always forbidden containers of const elements (e.g. vector, set). (C++98/03’s prohibition was crystal clear: elements must be Assignable, which const T isn’t. C++11/14’s prohibition is obscurely hidden, but it’s there.) Previously, VC accepted such containers due to non-Standard machinery in std::allocator. We’ve removed that machinery, so such containers now fail to compile.

Share

Visual Studio “14” CTP

Microsoft has released Visual Studio “14” CTP. You can read the announcement on Soma’s blog. Visual Studio “14” will most likely be available sometime in 2015.

Note: This is a CTP release, thus it should be installed in a test environment, such as a VM or a clean machine. Do not install on a machine with another version of Visual Studio installed.

Specifically for C++, there are quite a few improvements, such as:

  • Generalized lambda capture
  • User-defined literals in the language and standard library
  • Completed noexcept
  • Inline namespaces
  • Thread-safe “magic” statics
  • Unrestricted unions
  • All November 2013 compiler CTP features
  • Null forward iterators
  • quoted()
  • Heterogeneous associative lookup
  • integer_sequence
  • exchange()
  • get()
  • Dual-range equal(), is_permutation(), mismatch()
  • tuple_element_t
  • Filesystem “V3” Technical Specification (TS)
  • Object file size reductions
  • Debug checking fixes
  • Create declaration or definition
  • Native memory diagnostics
  • Refactored C Runtime (CRT): This CTP contains the first preview of the substantially refactored CRT. msvcr140.dll no longer exists. It is replaced by a trio of DLLs: vcruntime140.dll, appcrt140.dll, and desktopcrt140.dll.

Read Eric’s blog for a bit more details on those improvements.

Download the CTP.

Share

Introduction to WIC: How to use WIC to load an image, and draw it with tranparency using only GDI?

A while ago I wrote an article: “Introduction to WIC: How to use WIC to load an image, and draw it with GDI?”

The code in that article didn’t handle transparency.
It’s actually trivial to implement transparency in that sample code. Read the rest of this entry »

Share

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

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

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

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

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

Visual Studio 2012 Update 1 Now Available


The first update for Visual Studio 2012 has been released.
This update delivers bug fixes, but also new functionality. The new functionality in this first update primarily spans four areas: Windows development, SharePoint development, agile teams, and continuous quality.

We can now target Windows XP again with C++ code, and there have been a couple of C++ unit testing enhancements. For Windows Store applications, the update includes support for both mixed-mode managed/native debugging and for native ARM dump debugging.

Get more details about the update.
Download the update.

Share

Visual C++ November CTP, now with more C++11

As promised, Microsoft is releasing out-of-band updates for Visual C++. A preview of the first such update has now been released as the November 2012 Compiler CTP. This is a Customer Technology Preview and does not come with a ‘Go Live’ license, but it allows you to start experimenting and testing new features, and to provide feedback.

This November 2012 CTP contains a lot of new C++11 features:

  • Variadic templates
  • Uniform initialization and initializer_lists
  • Delegating constructors
  • Raw string literals
  • Explicit conversion operators
  • Default template arguments for function templates

More details, including installation instructions and how to give feedback can be found here.

Download the November 2012 CTP and start playing with these new C++11 features.

Share

Implementing a Thread-safe Singleton with C++11

Note: see my more recent article “Implementing a Thread-Safe Singleton with C++11 Using Magic Statics” for a more modern solution.

C++11 makes it easier to write a thread-safe singleton. Here is an example. The class definition of the singleton looks as follows:

#include <memory>
#include <mutex>

class CSingleton
{
public:
	virtual ~CSingleton() = default;
	static CSingleton& GetInstance();

private:
	static std::unique_ptr<CSingleton> m_instance;
	static std::once_flag m_onceFlag;
	CSingleton() = default;
	CSingleton(const CSingleton& src) = delete;
	CSingleton& operator=(const CSingleton& rhs) = delete;
};

The implementation of the GetInstance() method is very easy using C++11 std::call_once() and a lambda:

std::unique_ptr<CSingleton> CSingleton::m_instance;
std::once_flag CSingleton::m_onceFlag;

CSingleton& CSingleton::GetInstance()
{
	std::call_once(m_onceFlag,
		[] {
			m_instance.reset(new CSingleton);
	});
	return *m_instance.get();
}
Share

Kate’s C++ AMP Book

Kate Gregory (a fellow VC++ MVP) has published her book called “C++ AMP: Accelerated Massive Parallelism with Microsoft Visual C++”.

The official description is as follows.

Capitalize on the faster GPU processors in today’s computers with the C++ AMP code library—and bring massive parallelism to your project. With this practical book, experienced C++ developers will learn parallel programming fundamentals with C++ AMP through detailed examples, code snippets, and case studies. Learn the advantages of parallelism and get best practices for harnessing this technology in your applications.

Discover how to:

  • Gain greater code performance using graphics processing units (GPUs)
  • Choose accelerators that enable you to write code for GPUs
  • Apply thread tiles, tile barriers, and tile static memory
  • Debug C++ AMP code with Microsoft Visual Studio®
  • Use profiling tools to track the performance of your code

Find out more about this book here.

Share

BeCPP Meeting October

The next meeting of the Belgian C++ Users Group is planned for Tuesday October 16th 2012 at 18:30 in the Microsoft offices in Zaventem.

The agenda is as follows:

  • Session 1: An introduction to the C++ Network Library (Glyn Matthews)
  • Break
  • Session 2: Comparison between Unit Test Frameworks (Mark Van Peteghem)
  • Drink

Microsoft is sponsoring this event by providing the location, drinks and sandwiches.

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

Share