Scott Meyers - Effective Modern C++

Здесь есть возможность читать онлайн «Scott Meyers - Effective Modern C++» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Sebastopol, Год выпуска: 2014, ISBN: 2014, Издательство: O’Reilly, Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Effective Modern C++: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Effective Modern C++»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Coming to grips with C++11 and C++14 is more than a matter of familiarizing yourself with the features they introduce (e.g., auto type declarations, move semantics, lambda expressions, and concurrency support). The challenge is learning to use those features
— so that your software is correct, efficient, maintainable, and portable. That's where this practical book comes in. It describes how to write truly great software using C++11 and C++14 — i.e., using
C++.
Topics include:
■ The pros and cons of braced initialization,
specifications, perfect forwarding, and smart pointer make functions
■ The relationships among
,
, rvalue references, and universal references
■ Techniques for writing clear, correct,
lambda expressions
■ How
differs from
, how each should be used, and how they relate to C++'s concurrency API
■ How best practices in “old” C++ programming (i.e., C++98) require revision for software development in modern C++
Effective Modern C++ For more than 20 years,
'
books (
,
, and
) have set the bar for C++ programming guidance. His clear, engaging explanations of complex technical material have earned him a worldwide following, keeping him in demand as a trainer, consultant, and conference presenter. He has a Ph.D. in Computer Science from Brown University.
“After I learned the C++ basics, I then learned how to use C++ in production code from Meyers' series of Effective C++ books. Effective Modern C++ is the most important how-to book for advice on key guidelines, styles, and idioms to use modern C++ effectively and well. Don't own it yet? Buy this one. Now.”
Herb Sutter
Chair of ISO C++ Standards Committee and C++ Software Architect at Microsoft

Effective Modern C++ — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Effective Modern C++», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Values known during compilation are privileged. They may be placed in read-only memory, for example, and, especially for developers of embedded systems, this can be a feature of considerable importance. Of broader applicability is that integral values that are constant and known during compilation can be used in contexts where C++ requires an integral constant expression . Such contexts include specification of array sizes, integral template arguments (including lengths of std::arrayobjects), enumerator values, alignment specifiers, and more. If you want to use a variable for these kinds of things, you certainly want to declare it constexpr, because then compilers will ensure that it has a compile-time value:

int sz; // non-constexpr variable

constexpr auto arraySize1 = sz; // error! sz's value not

// known at compilation

std::array data1; // error! same problem

constexpr auto arraySize2 = 10; // fine, 10 is a

// compile-time constant

std::array data2; // fine, arraySize2

// is constexpr

Note that constdoesn't offer the same guarantee as constexpr, because constobjects need not be initialized with values known during compilation:

int sz; // as before

const auto arraySize = sz; // fine, arraySize is

// const copy of sz

std::array data; // error! arraySize's value

// not known at compilation

Simply put, all constexprobjects are const, but not all constobjects are constexpr. If you want compilers to guarantee that a variable has a value that can be used in contexts requiring compile-time constants, the tool to reach for is constexpr, not const.

Usage scenarios for constexprobjects become more interesting when constexprfunctions are involved. Such functions produce compile-time constants when they are called with compile-time constants . If they're called with values not known until runtime, they produce runtime values. This may sound as if you don't know what they'll do, but that's the wrong way to think about it. The right way to view it is this:

constexprfunctions can be used in contexts that demand compile-time constants. If the values of the arguments you pass to a constexprfunction in such a context are known during compilation, the result will be computed during compilation. If any of the arguments' values is not known during compilation, your code will be rejected.

• When a constexprfunction is called with one or more values that are not known during compilation, it acts like a normal function, computing its result at runtime. This means you don't need two functions to perform the same operation, one for compile-time constants and one for all other values. The constexprfunction does it all.

Suppose we need a data structure to hold the results of an experiment that can be run in a variety of ways. For example, the lighting level can be high, low, or off during the course of the experiment, as can the fan speed and the temperature, etc. If there are n environmental conditions relevant to the experiment, each of which has three possible states, the number of combinations is 3 . Storing experimental results for all combinations of conditions thus requires a data structure with enough room for 3 values. Assuming each result is an intand that n is known (or can be computed) during compilation, a std::arraycould be a reasonable data structure choice. But we'd need a way to compute 3 during compilation. The C++ Standard Library provides std::pow, which is the mathematical functionality we need, but, for our purposes, there are two problems with it. First, std::powworks on floating-point types, and we need an integral result. Second, std::powisn't constexpr(i.e., isn't guaranteed to return a compile-time result when called with compile-time values), so we can't use it to specify a std::array's size.

Fortunately, we can write the powwe need. I'll show how to do that in a moment, but first let's look at how it could be declared and used:

constexpr // pow's a constexpr func

int pow(int base, int exp) noexcept // that never throws

{

… // impl is below

}

constexpr auto numConds = 5; // # of conditions

std::arraypow(3, numConds)> results; // results has

// 3^numConds

// elements

Recall that the constexprin front of powdoesn't say that powreturns a constvalue, it says that if baseand expare compile-time constants, pow's result may be used as a compile-time constant. If baseand/or expare not compile-time constants, pow's result will be computed at runtime. That means that powcan not only be called to do things like compile-time-compute the size of a std::array, it can also be called in runtime contexts such as this:

auto base = readFromDB("base"); // get these values

auto exp = readFromDB("exponent"); // at runtime

auto baseToExp = pow(base, exp); // call pow function

// at runtime

Because constexprfunctions must be able to return compile-time results when called with compile-time values, restrictions are imposed on their implementations. The restrictions differ between C++11 and C++14.

In C++11, constexprfunctions may contain no more than a single executable statement: a return. That sounds more limiting than it is, because two tricks can be used to extend the expressiveness of constexprfunctions beyond what you might think. First, the conditional “ ?:” operator can be used in place of if-elsestatements, and second, recursion can be used instead of loops. powcan therefore be implemented like this:

constexpr int pow(int base, int exp) noexcept {

return (exp == 0 ? 1 : base * pow(base, exp - 1));

}

This works, but it's hard to imagine that anybody except a hard-core functional programmer would consider it pretty. In C++14, the restrictions on constexprfunctions are substantially looser, so the following implementation becomes possible:

constexpr int pow(int base, int exp) noexcept // C++14

{

auto result = 1;

for (int i = 0; i < exp; ++i) result *= base;

return result;

}

constexprfunctions are limited to taking and returning literal types , which essentially means types that can have values determined during compilation. In C++11, all built-in types except voidqualify, but user-defined types may be literal, too, because constructors and other member functions may be constexpr:

class Point {

public:

constexprPoint(double xVal = 0, double yVal = 0) noexcept

: x(xVal), y(yVal)

{}

constexprdouble xValue() const noexcept { return x; }

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Effective Modern C++»

Представляем Вашему вниманию похожие книги на «Effective Modern C++» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Effective Modern C++»

Обсуждение, отзывы о книге «Effective Modern C++» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x