Tag Archives: C++14

Codexpert – 2015 Articles Summary

Microsoft Libraries and C++ Programming Language

What’s next?

We planned to continue the Direct2D/DirectWrite series but also other articles about programming with C++ using Microsoft Windows libraries like MFC, ATL, Windows API and so on.

See also

Binary literals and digit separators

The C++14 standard provides two new small features to the language: binary literals and digit separators. They are already available in Clang 3.4 and GCC 4.9 and now Visual Studio 2015 RC has implemented them. They may not be something you can’t live without, but sometimes it’s convenient to have them. Let’s have a look.

In C++ it was possible to input integer literals in several bases: decimal, hexadecimal and octal. However, the binary base has been omitted (though other languages supported that). With C++14 binary is also supported and binary literals are introduced with the prefix 0b or 0B.

Binary literals can be used anywhere integral literals are expected.

What if you had to write large literals such as 0b101111000110000101001110, which is the binary representation of decimal 12345678? Sometimes it is convenient to separate groups of digits for more human readability.

C++14 defines the single quotation mark (') as a digit separator in integral and floating point literals. So the binary literal 0b101111000110000101001110 can be expressed in several ways:

or maybe in hexadecimal:

The position of the single quotation marks in the integral or floating point literals is irrelevant, they are simply ignored when determining the value of the literal. All the following are equivalent (but probably only the first and the last make sense).

Using Lambdas in MFC Applications – Part 1: Sorting Arrays

Beginning with Visual Studio 2010 which supports lambda expressions introduced by C++11 standard, you can handily sort an MFC array like in the following example:

Sorting CStringArray by using a lambda expression

Of course, you can write similar code for other types of MFC arrays like CArray, CUIntArray, and so on.
But also you can easily write a kind of “generic lambda” in order to sort any type of MFC arrays.

Using decltype to sort any type of MFC array

That’s pretty cool… However would be nice to be possible to get rid of “wordy” constructions like “decltype(*arr.GetData())” in the lambda’s formal parameters list. Good news! There is a proposal for next C++ standards: using auto type-specifier in order to make generic lambda expressions (which accept any type of arguments). And that is already supported in Visual Studio 2015.

Using generic (polymorphic) lambda expressions

Notes

  • Some people may claim that using MFC collection classes is obsolete and must use STL containers instead. That’s an old subject of arguing but it’s not in scope of this short article.
    It simply presents how to sort MFC arrays by using lambda expressions.

References and related articles

User defined literals

The C++ language defines various built-in literals (numerical, character, string, boolean and pointer) and a series of prefixes and suffixes to specify some of them. The suffix or prefix is part of the literal.

The C++11 standard introduced the possibility to create user-defined literals, that are basically built-in type literals (integer, float, char or string) followed by a used-defined suffix. User-defined literals enable the creation of new objects based on the built-in literal value and the applied user-defined suffix.

A bit of theory

A user-defined literal is treated as a call to a literal operator or a literal operator template. User-defined literals have two forms:

  • raw: a sequence of characters; the literal 0xBAD is in raw form is ‘0’, ‘x’, ‘B’, ‘A’, ‘D’
  • cooked: is the compiler interpreted type of the sequence of characters; the literal 0xBAD is the integer 2898 in cooked form.

User-defined literals:

  • support only the suffix form; defining prefixes is not possible;
  • begin with a underscore (‘_’); all suffixes that begin with any other character except underscore are reserved by the standard;
  • can be extended in both raw and cooked form; the exception is represented by strings that can only be extended in the cooked form

Cooked literals

The literal operator called for a cooked literal has following form:

Only several input types are allowed:

  • for integral literals (decimal, octal, hexadecimal or binary) the type is unsigned long long (the reason for unsigned is that the sign is not part of a numeric literal, but is in fact a unary operator applied to the numerical value).
  • for floating point types the type is long double:
  • for characters the type is char, wchar_t, char16_t or char32_t:
  • for strings the type is char const *, wchar_t const *, char16_t const * or char32_t const *:

Raw literals

Raw literals are supported only for integral and floating point types. The literal operator called for a cooked literal has following form (notice that the operator does not take a second parameter to indicate the size, the string is null-terminated):

Parsing this array of characters may involve loops, variable declaration, function calls, etc. As a result this form of the literal operator cannot be constexpr, which means it cannot be evaluated at compile time.

An alternative way of processing raw literals is with a literal operator variadic template. The purpose of a variadic template literal operator is to make the literal transformation at compile time. The form of the literal operator template is:

A bit of practice

Let’s take the following example where we declare a buffer of 4 KB.

This is identical to the following declaration (you’d usually expect)

It is made possible by the existence of a literal operator with the following form:

If the literal operator was not a constexpr then the compiler would trigger an error when declaring the buffer variable, because the size of the array must be known at compile time. You’d still be able to use the user-defined literal but in runtime contexts, such as sizing a vector.

In the next example we define a user-defined literal for expressing temperatures in Fahrenheit degrees. Supposing the Celsius degrees are the norm, we can write sometime like this:

and use it like in the following example:

The return type of the literal operator can be any type; it does not have to be a built-in type like in the previous examples. Given the following hierarchy of classes we can create user-defined literals that enable the creation of developer and quality assurer objects:

In the next example we want to express latitudes, such as 66°33’39”N (the Arctic Circle). (Notice that the following types and just some simple implementations for demo purposes only).

With this in place we can create objects like this:

Values like Latitude(66, 0, 0) are not very intuitive. Even though it’s more verbose it may be more desirable to be able to create objects like this:

That is possible if we define deg(), min() and sec() as following:

User-defined literals makes is more simple and more natural. By transforming the above functions into literal operators we can simplify the syntax.

As a result we can now create latitudes like this:

It should be very simple to develop this to support longitudes. You don’t have to add more literal operators, just the Longitude type and the appropriate overloaded operators for it.

Standard user-defined literals

C++14 defines several literal operators:

  • operator""if, operator""i and operator""il for creating a std::complex value

  • operator""h, operator""min, operator""s, operator""ms, operator""us, operator""ns for creating a std::chrono::duration value

    This is equivalent to the following (longer) form in C++11:

  • operator""s for converting a character array literal to a std::basic_string

Notice that all these literal operators are defined in separate namespaces that you have to use.

References

Compiler support

User defined literals are supported by major compilers starting with the following version:

See also:

Function return type deduction in C++14

C++11 introduced the auto keyword as a placeholder for types. It could be used for declaring variables but also for the return type of a function, given than you use a new syntax with a trailing type at the end of the function.

or

This is a bit cumbersome and too explicit so C++14 takes the next step and makes the trailing return type unnecessary. Under C++14 the above examples can be simply written as:

and

There are several things to keep in mind:

  • if a function has more than one return statement they all must deduce the same type
  • a recursive function can have an auto return type only if it has a non-recursive return statement before the recursive call.
  • a function with an auto return type can be forward declared, but cannot be used until it has been defined

In my personal opinion auto return type should be used with caution. It can make the code harder to read and maintain (you don’t know the type just by looking at the signature), harder to document (automatic documenting tools use the signature to produce documentation), and can lead to situations when the developer expects one return type but the compiler generates another.

Additional readings:

Farewell to new and delete

C++11 introduced several smart pointers (residing in the <memory> header):

  • std::shared_ptr: retains shared ownership of an object, that is destroyed when the last shared_ptr that holds a reference to it is destroyed or assigned another pointer.
  • std::unique_ptr: retains sole ownership of an object, that is destroyed when the unique_ptr goes out of scope
  • std::weak_ptr: retains a non-owning reference to an object managed by a shared_ptr. It does not participate in the reference counter of the shared pointer. It is mainly use to break circular dependencies.

While these smart pointers manage resources automatically, so there is no need to delete object explicitly, they still require explicit instantiation with new for the managed resource.

C++11 introduced std::make_shared, a free function that constructs an object and wraps it in a std::shared_ptr object.

C++14 introduces another free function, std::make_unique, that constructs an object and wraps it in a std::unique_ptr object.

With these smart pointer and functions available there is no need any more to use new and delete in your C++ code. Besides avoiding explicit allocation and release these functions have another important advantage: they prevent memory leaks that could happen in the context of function calls. You can read Herb Sutter’s GotW #102: Exception-Safe Function Calls for details about this problem.