Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
roth_stephan_clean_c20_sustainable_software_development_patt.pdf
Скачиваний:
29
Добавлен:
27.03.2023
Размер:
7.26 Mб
Скачать

Chapter 5 Advanced Concepts of Modern C++

The Compiler Is Your Colleague

As I have written elsewhere, the advent of the C++11 language standard fundamentally changed the way that modern and clean C++ programs are designed. Styles, patterns, and idioms that programmers are using while writing modern C++ code are totally different than before. Besides the fact that the newer C++ standards offer many useful new features to write C++ code that is well maintainable, understandable, efficient, and testable, something else has still changed: the role of the compiler!

In former times, the compiler was just a tool to translate the source code into executable machine instructions (object code) for a computer; but now it is increasingly becoming a tool to support the developer on different levels. The three guiding principles for working with a C++ compiler are the following:

•\

Everything that can be done at compile time should be done at

 

compile time.

•\

Everything that can be checked at compile time should be checked at

 

compile time.

•\

Everything the compiler can know about a program should be

 

determined by the compiler.

In former chapters and sections, you’ve experienced in some spots how the compiler can support you. For instance, in the section about move semantics, we’ve seen that modern C++ compilers are able to perform manifold sophisticated optimizations (e.g., copy elision) that we don’t have to care about anymore. In the following sections, I show you how the compiler can support developers and make many things much easier.

Automatic Type Deduction

Do you remember the meaning of the C++ keyword auto before C++11? I’m pretty sure that it was probably the least-known and used keyword in the language. Maybe you remember that auto in C++98 or C++03 was a so-called storage class specifier and has been used to define that a local variable has “automatic duration,” that is, the variable is created at the point of definition and destroyed when the block it was part of is exited. Since C++11, all variables have automatic duration per default unless otherwise

specified. Thus, the previous semantics of auto were becoming useless, and the keyword got a completely new meaning.

159

Chapter 5 Advanced Concepts of Modern C++

Nowadays, auto is used for automatic type deduction, sometimes also called type inference. If it is used as a type specifier for a variable, it specifies that the type of the variable that is being declared will be automatically deduced (or inferred) from its initializer, like in the following examples:

auto theAnswerToAllQuestions = 42; auto iter = begin(myMap);

const auto gravitationalAccelerationOnEarth = 9.80665; constexpr auto sum = 10 + 20 + 12;

auto strings = { "The", "big", "brown", "fox", "jumps", "over", "the", "lazy", "dog" };

auto numberOfStrings = strings.size();

ARGUMENT DEPENDENT NAME LOOKUP (ADL)

Argument Dependent (Name) Lookup (ADL), also known as Koenig Lookup (named after the American computer scientist Andrew Koenig), is a compiler technique to look up an unqualified function name (that is, a function name without a prefixed namespace qualifier) depending on the types of the arguments passed to the function at its call site.

Suppose you have a std::map<K, T> (defined in the <map> header) like the following one:

#include <map> #include <string>

std::map<unsigned int, std::string> words;

Due to ADL, it is not necessary to specify the namespace std if you use the begin() or end() function to retrieve an iterator from the container. You can simply write:

auto wordIterator = begin(words);

The compiler does not just look at the local scope, but also the namespaces that contain the argument’s type (in this case, the namespace of map<K, T>, which is std). Thus, in the previous example, the compiler finds a fitting begin() function for maps in the std-­ namespace.

In some cases, you need to explicitly define the namespace, for example, if you want to use std::begin() and std::end() with a simple C-style array.

160

Chapter 5 Advanced Concepts of Modern C++

On first sight, using auto instead of a concrete type seems to be a convenience feature. Developers are no longer forced to remember a type’s name. They simply write auto, const auto, auto& (for references), or const auto& (for const references), and the compiler does the rest, because it knows the type of the assigned value. Automatic type deduction can of course also be used in conjunction with constexpr (see the section about computations at compile time).

Do not be afraid to use auto (or auto& and const auto&) as much as possible. The code is still statically typed, and the types of the variables are clearly defined. For instance, the type of the variable strings from the previous example

is std::initializer_list<const char*>, the type of numberOfStrings is std::initializer_list<const char*>::size_type.

The only thing that developers should be aware of is that auto will strip const and reference qualifiers, and hence a careless use of it can result in unwanted copies being made. Especially in range-based for loops, this can easily be overlooked:

#include

<string>

 

#include

<vector>

 

// And somewhere in the code...

 

std::vector<std::string> aLotOfStrings { ..........

};

for (auto str : aLotOfStrings) {

// Attention: A copy of each string will be made!

}

for (const auto& str : aLotOfStrings) { // Copies are avoided.

}

STD::INITIALIZER_LIST<T> [C++11]

In former days (prior C++11), if we wanted to initialize a Standard Library container using literals, we had to do the following:

std::vector<int> integerSequence; integerSequence.push_back(14); integerSequence.push_back(33); integerSequence.push_back(69); // ...and so on...

161

Chapter 5 Advanced Concepts of Modern C++

Since C++11, we can simply do it this way:

std::vector<int> integerSequence { 14, 33, 69, 104, 222, 534 };

The reason for this is that std::vector<T> has an overloaded constructor that accepts a so-­ called initializer list as a parameter. An initializer list is an object of type std::initializer_ list<T> (defined in the <initializer_list> header).

An instance of type std::initializer_list<T> is automatically constructed when you use a list of comma-separated literals that are surrounded with a pair of curly braces, a so-called braced-init-list. You can equip your own classes with constructors that can accept initializer lists, as shown in this example:

#include <string> #include <vector>

using WordList = std::vector<std::string>;

class LexicalRepository { public:

explicit LexicalRepository(const std::initializer_list<const char*>& words) { wordList.insert(begin(wordList), begin(words), end(words));

}

// ...

private:

WordList wordList;

};

int main() {

LexicalRepository repo { "The", "big", "brown", "fox", "jumps", "over", "the", "lazy", "dog" };

// ...

return 0;

}

Note  This initializer list should not be confused with a class of its constructor member initializer list!

162

Chapter 5 Advanced Concepts of Modern C++

Since C++14, the automatic return type deduction for functions is also supported. This is especially helpful when a return type has a difficult-to-remember or unutterable name, which is often the case when dealing with complex non-standard data types as return types.

auto function() {

std::vector<std::map<std::pair<int, double>, int>> returnValue; // ...fill 'returnValue' with data...

return returnValue;

}

We haven’t discussed lambda expressions until now (they will be discussed in detail in Chapter 7), but C++11 and higher lets you store lambda expressions in named variables:

auto square = [](const int x) { return x * x; };

Maybe you’re wondering why, in Chapter 4, I told you that an expressive and good name is important for the readability of the code and should be a major goal for every professional programmer. Now I promote the use of the keyword auto, which makes it more difficult to recognize the type of a variable quickly just by reading the code. Isn’t that a contradiction?

My clear answer is this: no, quite the contrary! Apart from a few exceptions, auto can raise the readability of the code. Look at the two alternatives of a variable assignment in Listing 5-15.

Listing 5-15.  Which One of the Following Two Versions Would You Prefer?

// 1st version: without auto std::shared_ptr<controller::CreateMonthlyInvoicesController> createMonthlyInvoicesController =

std::make_shared<controller::CreateMonthlyInvoicesController>();

// 2nd version: with auto:

auto createMonthlyInvoicesController = std::make_shared<controller::CreateMonthlyInvoicesController>();

From my point of view, the version using auto is easier to read. There is no need to repeat the type explicitly, because it is pretty clear from its initializer what type

163