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++», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

Item 3: Understand decltype.

decltypeis an odd creature. Given a name or an expression, decltypetells you the name's or the expression's type. Typically, what it tells you is exactly what you'd predict. Occasionally however, it provides results that leave you scratching your head and turning to reference works or online Q&A sites for revelation.

We'll begin with the typical cases — the ones harboring no surprises. In contrast to what happens during type deduction for templates and auto (see Items 1and 2), decltypetypically parrots back the exact type of the name or expression you give it:

const int i = 0; // decltype(i) is const int

bool f(const Widget& w); // decltype(w) is const Widget&

// decltype(f) is bool(const Widget&)

struct Point {

int x, y; // decltype(Point::x) is int

}; // decltype(Point::y) is int

Widget w; // decltype(w) is Widget

if (f(w)) … // decltype(f(w)) is bool

template // simplified version of std::vector

class vector {

public:

T& operator[](std::size_t index);

};

vector v; // decltype(v) is vector

if (v[0] == 0) … // decltype(v[0]) is int&

See? No surprises.

In C++11, perhaps the primary use for decltypeis declaring function templates where the function's return type depends on its parameter types. For example, suppose we'd like to write a function that takes a container that supports indexing via square brackets (i.e., the use of “ []”) plus an index, then authenticates the user before returning the result of the indexing operation. The return type of the function should be the same as the type returned by the indexing operation.

operator[]on a container of objects of type Ttypically returns a T&. This is the case for std::deque, for example, and it's almost always the case for std::vector. For std::vector, however, operator[]does not return a bool&. Instead, it returns a brand new object. The whys and hows of this situation are explored in Item 6, but what's important here is that the type returned by a container's operator[]depends on the container.

decltypemakes it easy to express that. Here's a first cut at the template we'd like to write, showing the use of decltypeto compute the return type. The template needs a bit of refinement, but we'll defer that for now:

template // works, but

autoauthAndAccess(Container& c, Index i) // requires

-> decltype(c[i]) // refinement

{

authenticateUser();

return c[i];

}

The use of autobefore the function name has nothing to do with type deduction. Rather, it indicates that C++11's trailing return type syntax is being used, i.e., that the function's return type will be declared following the parameter list (after the “ ->”). A trailing return type has the advantage that the function's parameters can be used in the specification of the return type. In authAndAccess, for example, we specify the return type using cand i. If we were to have the return type precede the function name in the conventional fashion, cand iwould be unavailable, because they would not have been declared yet.

With this declaration, authAndAccessreturns whatever type operator[]returns when applied to the passed-in container, exactly as we desire.

C++11 permits return types for single-statement lambdas to be deduced, and C++14 extends this to both all lambdas and all functions, including those with multiple statements. In the case of authAndAccess, that means that in C++14 we can omit the trailing return type, leaving just the leading auto. With that form of declaration, auto does mean that type deduction will take place. In particular, it means that compilers will deduce the function's return type from the function's implementation:

template // C++14;

autoauthAndAccess(Container& c, Index i) // not quite

{ // correct

authenticateUser();

return c[i]; // return type deduced from c[i]

}

Item 2explains that for functions with an autoreturn type specification, compilers employ template type deduction. In this case, that's problematic. As we've discussed, operator[]for most containers-of- Treturns a T&, but Item 1explains that during template type deduction, the reference-ness of an initializing expression is ignored. Consider what that means for this client code:

std::deque d;

authAndAccess(d, 5) = 10; // authenticate user, return d[5],

// then assign 10 to it;

// this won't compile!

Here, d[5]returns an int&, but autoreturn type deduction for authAndAccesswill strip off the reference, thus yielding a return type of int. That int, being the return value of a function, is an rvalue, and the code above thus attempts to assign 10 to an rvalue int. That's forbidden in C++, so the code won't compile.

To get authAndAccessto work as we'd like, we need to use decltypetype deduction for its return type, i.e., to specify that authAndAccessshould return exactly the same type that the expression c[i]returns. The guardians of C++, anticipating the need to use decltypetype deduction rules in some cases where types are inferred, make this possible in C++14 through the decltype(auto)specifier. What may initially seem contradictory ( decltype and auto?) actually makes perfect sense: autospecifies that the type is to be deduced, and decltypesays that decltyperules should be used during the deduction. We can thus write authAndAccesslike this:

template // C++14; works,

decltype(auto) // but still

authAndAccess(Container& c, Index i) // requires

{ // refinement

authenticateUser();

return c[i];

}

Now authAndAccesswill truly return whatever c[i]returns. In particular, for the common case where c[i]returns a T&, authAndAccesswill also return a T&, and in the uncommon case where c[i]returns an object, authAndAccesswill return an object, too.

The use of decltype(auto)is not limited to function return types. It can also be convenient for declaring variables when you want to apply the decltypetype deduction rules to the initializing expression:

Widget w;

const Widget& cw = w;

automyWidget1 = cw; // auto type deduction:

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

Интервал:

Закладка:

Сделать

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

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


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

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

x