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

Chapter 5 Advanced Concepts of Modern C++

•\ Hard to misuse. Use appropriate parameter and return types and avoid long parameter lists (see the section entitled “Arguments and Return Values” in Chapter 4). If values have semantics, strongly typed parameters instead of primitive data types (int, double, ...) should be used for them, as described in the section “Type-Rich Programming” in this chapter. Don’t use a string if a better type exists.

•\ Don’t forget that exceptions are also part of an interface. Throw exceptions only to indicate true exceptional conditions, i.e. don’t force users of your interface to use exceptions for normal control flow. This aspect has been discussed in detail in the previous section entitled “Proper Exception and Error Handling.”

•\ Provide a suite of well-crafted unit tests for your API. As discussed in Chapter 2, a suite of good tests is not only a sign of the quality awareness of the developers, but they are also good examples for users that can show how to use the API.

In addition to these general good practices for interface design, modern C++ offers further possibilities to specify interfaces, which I briefly discuss in the following and last sections of this chapter:

•\

Attributes (since C++11)

•\

Concepts (new since C++20)

Attributes

C++ Attributes were introduced with C++11 and regularly extended with the following language standards. Maybe you know a very similar concept in programming language Java, which is called annotations. Some attributes are part of the C++ language standard, others are compiler-specific.

In simple terms, an attribute is an expression surrounded with double square brackets to give instructions to the compiler, like this:

[[attr]]

Multiple attributes can be specified as a comma-separated list:

[[attr1, attr2, attr3]]

210

Chapter 5 Advanced Concepts of Modern C++

Specific kinds of attributes can also have an argument:

[[attr(argument)]]

With attributes, software developers can specify additional information or instructions for the compiler, e.g., to enforce constraints (conditions), optimize certain sections of code, or do some specific code generations. Basically, attributes can be applied to almost every C++ programming language construct, e.g., types, variables, functions/methods, names, code blocks, and so on. However, certain attributes only make sense for very specific parts of the code. And they can also be very useful to design interfaces.

In the following sections, I introduce some of the attributes that are defined in the C++ standard and that can be used in interface design.

noreturn (since C++11)

The attribute [[noreturn]] can be used to mark a function from which the program flow does not return.

[[noreturn]] void function() { while (true) {

// ... do something ...

}

}

Perhaps you might wonder what this is good for? Well, if you implement a function that should intentionally not return (e.g., an endless loop to process events), but does so anyway due to a programming error, you’ll get a compiler warning:

warning: 'noreturn' function does return

deprecated (since C++14)

Sometimes it is necessary to take back parts of an already published interface. As mentioned, ideally this should not happen, because users of an interface have made themselves dependent on it. At the same time, it is sometimes unavoidable in reality.

A good idea is not to remove the published part of the interface immediately, but to prepare the users that this could happen in the future. In other words, it is advisable to

211

Chapter 5 Advanced Concepts of Modern C++

give your API users a grace period. Therefore, you can mark such entities as deprecated, meaning their use is allowed, but discouraged for some reason.

class SomeType { public:

[[deprecated]] void doSomething() { // ...

}

};

It is also possible to specify a rationale as a string-literal to explain why the use is discouraged:

class SomeType { public:

[[deprecated("This function will be removed in future versions, " "use SomeType::doSomethingNew() instead!")]]

void doSomething() { // ...

}

void doSomethingNew() { // ...

}

};

nodiscard (since C++17)

With the help of the [[nodiscard]] attribute interface, designers can indicate that a return value of a function shouldn’t be ignored. If the return value is ignored at the call site, the compiler generates a warning. Since C++20, you can also specify a rationale as a string-literal to explain to users why ignoring the return value is discouraged. See Listing 5-31.

212

Chapter 5 Advanced Concepts of Modern C++

Listing 5-31.  The [[nodiscard]] Attribute Reminds Users to Accept the Return Value

#include <memory>

class SomeType { };

using SomeTypePtr = std::shared_ptr<SomeType>;

class ObjectFactory { public:

[[nodiscard]] SomeTypePtr createInstance() const { return std::make_shared<SomeType>();

}

};

int main() { ObjectFactory factory;

auto instance = factory.createInstance(); // OK! factory.createInstance(); // Compiler warning! return 0;

}

maybe_unused (since C++17)

This attribute can be used to mark entities that might not be used. Thus, a compiler warning can be suppressed, which is generated when variables, parameters of functions or methods, data types, and other entities are declared, but not used.

For instance, depending on the configured warning level of your compiler, the following piece of code will produce a warning like "'param2': unreferenced formal parameter":

int function(const int param1, const int param2) { return param1 + param1;

}

int main() { function(10, 20); return 0;

}

213

Chapter 5 Advanced Concepts of Modern C++

With the attribute [[maybe_unused]], this parameter can be marked so that the compiler warning is suppressed.

int function(const int param1, [[maybe_unused]] const int param2) { return param1 + param1;

}

You might be wondering how you’d use this attribute. You might ask yourself, who intentionally introduces a function parameter that is not used inside the function?

Think about conditional compiling with C++ templates. Listing 5-32 shows a simple example.

Listing 5-32.  If Only Param1 Is Needed, You’ll Get No Warning

#include <type_traits>

template<typename T, typename U>

void function(T param1, [[maybe_unused]] U param2) { if constexpr (std::is_floating_point<U>::value) {

//...code that uses 'param1' and 'param2'...

}else {

//...code that uses 'param1' only...

}

}

int main() { function(10, 20.0); function(10, 20); return 0;

}

In the main() function, we see two instantiations of the template function(): the first with one int and one double, and the second one with two ints. In the implementation of function(), we can see a constexpr if, or in other words, a compile-time-if, a new language feature that was introduced with C++17. This feature allows template designers to discard branches of an if statement at compile-time based on a constant expression condition. In our case, it is a type trait (defined in the <type_traits> header) that inspects the type U of param2 and returns true if it is a floating­-­point type. So, instantiating the template with two ints would result in an unused param2.

214