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

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

Интервал:

Закладка:

Сделать

The C++98 approach to preventing use of these functions is to declare them privateand not define them. For example, near the base of the iostreams hierarchy in the C++ Standard Library is the class template basic_ios. All istream and ostream classes inherit (possibly indirectly) from this class. Copying istreams and ostreams is undesirable, because it's not really clear what such operations should do. An istreamobject, for example, represents a stream of input values, some of which may have already been read, and some of which will potentially be read later. If an istream were to be copied, would that entail copying all the values that had already been read as well as all the values that would be read in the future? The easiest way to deal with such questions is to define them out of existence. Prohibiting the copying of streams does just that.

To render istream and ostream classes uncopyable, basic_iosis specified in C++98 as follows (including the comments):

template >

class basic_ios : public ios_base {

public:

private:

basic_ios(const basic_ios&); // not defined

basic_ios& operator=(const basic_ios&); // not defined

};

Declaring these functions privateprevents clients from calling them. Deliberately failing to define them means that if code that still has access to them (i.e., member functions or friends of the class) uses them, linking will fail due to missing function definitions.

In C++11, there's a better way to achieve essentially the same end: use “ = delete” to mark the copy constructor and the copy assignment operator as deleted functions . Here's the same part of basic_iosas it's specified in C++11:

template >

class basic_ios : public ios_base {

public:

basic_ios(const basic_ios& ) = delete;

basic_ios& operator=(const basic_ios&) = delete;

};

The difference between deleting these functions and declaring them privatemay seem more a matter of fashion than anything else, but there's greater substance here than you might think. Deleted functions may not be used in any way, so even code that's in member and friendfunctions will fail to compile if it tries to copy basic_iosobjects. That's an improvement over the C++98 behavior, where such improper usage wouldn't be diagnosed until link-time.

By convention, deleted functions are declared public, not private. There's a reason for that. When client code tries to use a member function, C++ checks accessibility before deleted status. When client code tries to use a deleted privatefunction, some compilers complain only about the function being private, even though the function's accessibility doesn't really affect whether it can be used. It's worth bearing this in mind when revising legacy code to replace private-and-not-defined member functions with deleted ones, because making the new functions public will generally result in better error messages.

An important advantage of deleted functions is that any function may be deleted, while only member functions may be private. For example, suppose we have a non-member function that takes an integer and returns whether it's a lucky number:

bool isLucky(int number);

C++'s C heritage means that pretty much any type that can be viewed as vaguely numerical will implicitly convert to int, but some calls that would compile might not make sense:

if (isLucky('a')) … // is 'a' a lucky number?

if (isLucky(true)) … // is "true"?

if (isLucky(3.5)) … // should we truncate to 3

// before checking for luckiness?

If lucky numbers must really be integers, we'd like to prevent calls such as these from compiling.

One way to accomplish that is to create deleted overloads for the types we want to filter out:

bool isLucky(int number); // original function

bool isLucky(char) = delete; // reject chars

bool isLucky(bool) = delete; // reject bools

bool isLucky(double) = delete; // reject doubles and

// floats

(The comment on the doubleoverload that says that both doubles and floats will be rejected may surprise you, but your surprise will dissipate once you recall that, given a choice between converting a floatto an intor to a double, C++ prefers the conversion to double. Calling isLuckywith a floatwill therefore call the doubleoverload, not the intone. Well, it'll try to. The fact that that overload is deleted will prevent the call from compiling.)

Although deleted functions can't be used, they are part of your program. As such, they are taken into account during overload resolution. That's why, with the deleted function declarations above, the undesirable calls to isLuckywill be rejected:

if (isLucky('a')) … // error! call to deleted function

if (isLucky(true)) … // error!

if (isLucky(3.5f)) … // error!

Another trick that deleted functions can perform (and that private member functions can't) is to prevent use of template instantiations that should be disabled. For example, suppose you need a template that works with built-in pointers ( Chapter 4's advice to prefer smart pointers to raw pointers notwithstanding):

template

void processPointer(T* ptr);

There are two special cases in the world of pointers. One is void*pointers, because there is no way to dereference them, to increment or decrement them, etc. The other is char*pointers, because they typically represent pointers to C-style strings, not pointers to individual characters. These special cases often call for special handling, and, in the case of the processPointertemplate, let's assume the proper handling is to reject calls using those types. That is, it should not be possible to call processPointerwith void*or char*pointers.

That's easily enforced. Just delete those instantiations:

template<>

void processPointer(void*) = delete;

template<>

void processPointer(char*) = delete;

Now, if calling processPointerwith a void*or a char*is invalid, it's probably also invalid to call it with a const void*or a const char*, so those instantiations will typically need to be deleted, too:

template<>

void processPointer(const void*) = delete;

template<>

void processPointer(const char*) = delete;

And if you really want to be thorough, you'll also delete the const volatile void*and const volatile char*overloads, and then you'll get to work on the overloads for pointers to the other standard character types: std::wchar_t, std::char16_t, and std::char32_t.

Interestingly, if you have a function template inside a class, and you'd like to disable some instantiations by declaring them private(a la classic C++98 convention), you can't, because it's not possible to give a member function template specialization a different access level from that of the main template. If processPointerwere a member function template inside Widget, for example, and you wanted to disable calls for void*pointers, this would be the C++98 approach, though it would not compile:

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

Интервал:

Закладка:

Сделать

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

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


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

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

x