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

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

Интервал:

Закладка:

Сделать
Things to Remember

decltypealmost always yields the type of a variable or expression without any modifications.

• For lvalue expressions of type Tother than names, decltypealways reports a type of T&.

• C++14 supports decltype(auto), which, like auto, deduces a type from its initializer, but it performs the type deduction using the decltyperules.

Item 4: Know how to view deduced types.

The choice of tools for viewing the results of type deduction is dependent on the phase of the software development process where you want the information. We'll explore three possibilities: getting type deduction information as you edit your code, getting it during compilation, and getting it at runtime.

IDE Editors

Code editors in IDEs often show the types of program entities (e.g., variables, parameters, functions, etc.) when you do something like hover your cursor over the entity. For example, given this code,

const int theAnswer = 42;

auto x= theAnswer;

auto y= &theAnswer;

an IDE editor would likely show that x's deduced type was intand y's was const int*.

For this to work, your code must be in a more or less compilable state, because what makes it possible for the IDE to offer this kind of information is a C++ compiler (or at least the front end of one) running inside the IDE. If that compiler can't make enough sense of your code to parse it and perform type deduction, it can't show you what types it deduced.

For simple types like int, information from IDEs is generally fine. As we'll see soon, however, when more complicated types are involved, the information displayed by IDEs may not be particularly helpful.

Compiler Diagnostics

An effective way to get a compiler to show a type it has deduced is to use that type in a way that leads to compilation problems. The error message reporting the problem is virtually sure to mention the type that's causing it.

Suppose, for example, we'd like to see the types that were deduced for xand yin the previous example. We first declare a class template that we don't define. Something like this does nicely:

template // declaration only for TD;

class TD; // TD == "Type Displayer"

Attempts to instantiate this template will elicit an error message, because there's no template definition to instantiate. To see the types for xand y, just try to instantiate TD with their types:

TD xType; // elicit errors containing

TD yType; // x's and y's types

I use variable names of the form variableNameType, because they tend to yield error messages that help me find the information I'm looking for. For the code above, one of my compilers issues diagnostics reading, in part, as follows (I've highlighted the type information we're after):

error: aggregate 'TD< int> xType' has incomplete type and

cannot be defined

error: aggregate 'TD< const int *> yType' has incomplete type

and cannot be defined

A different compiler provides the same information, but in a different form:

error: 'xType' uses undefined class 'TD< int>'

error: 'yType' uses undefined class 'TD< const int *>'

Formatting differences aside, all the compilers I've tested produce error messages with useful type information when this technique is employed.

Runtime Output

The printfapproach to displaying type information (not that I'm recommending you use printf) can't be employed until runtime, but it offers full control over the formatting of the output. The challenge is to create a textual representation of the type you care about that is suitable for display. “No sweat,” you're thinking, “it's typeidand std::type_info::nameto the rescue.” In our continuing quest to see the types deduced for xand y, you may figure we can write this:

std::cout << typeid(x).name()<< '\n'; // display types for

std::cout << typeid(y).name()<< '\n'; // x and y

This approach relies on the fact that invoking typeid on an object such as xor yyields a std::type_infoobject, and std::type_infohas a member function, name, that produces a C-style string (i.e., a const char*) representation of the name of the type.

Calls to std::type_info::name are not guaranteed to return anything sensible, but implementations try to be helpful. The level of helpfulness varies. The GNU and Clang compilers report that the type of xis “ i”, and the type of yis “ PKi”, for example. These results make sense once you learn that, in output from these compilers, “ i” means “ int” and “ PK” means “pointer to konst const.” (Both compilers support a tool, c++filt, that decodes such “mangled” types.) Microsoft's compiler produces less cryptic output: “ int” for xand “ int const *” for y.

Because these results are correct for the types of xand y, you might be tempted to view the type-reporting problem as solved, but let's not be hasty. Consider a more complex example:

template // template function to

void f(const T& param); // be called

std::vector createVec(); // factory function

const auto vw = createVec(); // init vw w/factory return

if (!vw.empty()) {

f(&vw[0]); // call f

}

This code, which involves a user-defined type ( Widget), an STL container ( std::vector), and an autovariable ( vw), is more representative of the situations where you might want some visibility into the types your compilers are deducing. For example, it'd be nice to know what types are inferred for the template type parameter Tand the function parameter paramin f.

Loosing typeidon the problem is straightforward. Just add some code to fto display the types you'd like to see:

template

void f(const T& param) {

using std::cout;

cout << "T = " << typeid(T).name()<< '\n'; // show T

cout << "param = " << typeid(param).name()<< '\n'; // show

… // param's

} // type

Executables produced by the GNU and Clang compilers produce this output:

T = PK6Widget

param = PK6Widget

We already know that for these compilers, PK means “pointer to const,” so the only mystery is the number 6. That's simply the number of characters in the class name that follows ( Widget). So these compilers tell us that both Tand param are of type const Widget*.

Microsoft's compiler concurs:

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

Интервал:

Закладка:

Сделать

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

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


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

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

x