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

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

Интервал:

Закладка:

Сделать

A raw pointer. With this approach, if Ais destroyed, but Ccontinues to point to B, Bwill contain a pointer to Athat will dangle. Bwon't be able to detect that, so Bmay inadvertently dereference the dangling pointer. That would yield undefined behavior.

A std::shared_ptr . In this design, Aand Bcontain std::shared_ptrs to each other. The resulting std::shared_ptrcycle ( Apoints to Band Bpoints to A) will prevent both Aand B from being destroyed. Even if Aand Bare unreachable from other program data structures (e.g., because Cno longer points to B), each will have a reference count of one. If that happens, Aand Bwill have been leaked, for all practical purposes: it will be impossible for the program to access them, yet their resources will never be reclaimed.

A std::weak_ptr . This avoids both problems above. If Ais destroyed, B's pointer back to it will dangle, but Bwill be able to detect that. Furthermore, though Aand Bwill point to one another, B's pointer won't affect A's reference count, hence can't keep Afrom being destroyed when std::shared_ptrs no longer point to it.

Using std::weak_ptris clearly the best of these choices. However, it's worth noting that the need to employ std::weak_ptrs to break prospective cycles of std::shared_ptrs is not terribly common. In strictly hierarchal data structures such as trees, child nodes are typically owned only by their parents. When a parent node is destroyed, its child nodes should be destroyed, too. Links from parents to children are thus generally best represented by std::unique_ptrs. Back-links from children to parents can be safely implemented as raw pointers, because a child node should never have a lifetime longer than its parent. There's thus no risk of a child node dereferencing a dangling parent pointer.

Of course, not all pointer-based data structures are strictly hierarchical, and when that's the case, as well as in situations such as caching and the implementation of lists of observers, it's nice to know that std::weak_ptrstands at the ready.

From an efficiency perspective, the std::weak_ptrstory is essentially the same as that for std::shared_ptr. std::weak_ptrobjects are the same size as std::shared_ptrobjects, they make use of the same control blocks as std::shared_ptrs (see Item 19), and operations such as construction, destruction, and assignment involve atomic reference count manipulations. That probably surprises you, because I wrote at the beginning of this Item that std::weak_ptrs don't participate in reference counting. Except that's not quite what I wrote. What I wrote was that std::weak_ptrs don't participate in the shared ownership of objects and hence don't affect the pointed-to object's reference count . There's actually a second reference count in the control block, and it's this second reference count that std::weak_ptrs manipulate. For details, continue on to Item 21.

Things to Remember

• Use std::weak_ptrfor std::shared_ptr-like pointers that can dangle.

• Potential use cases for std::weak_ptrinclude caching, observer lists, and the prevention of std::shared_ptrcycles.

Item 21: Prefer std::make_uniqueand std::make_sharedto direct use of new.

Let's begin by leveling the playing field for std::make_uniqueand std::make_shared. std::make_sharedis part of C++11, but, sadly, std::make_uniqueisn't. It joined the Standard Library as of C++14. If you're using C++11, never fear, because a basic version of std::make_uniqueis easy to write yourself. Here, look:

template

std::unique_ptr make_unique(Ts&&... params) {

return std::unique_ptr(new T(std::forward(params)...));

}

As you can see, make_uniquejust perfect-forwards its parameters to the constructor of the object being created, constructs a std::unique_ptrfrom the raw pointer newproduces, and returns the std::unique_ptrso created. This form of the function doesn't support arrays or custom deleters (see Item 18), but it demonstrates that with only a little effort, you can create make_uniqueif you need to. [9] To create a full-featured make_unique with the smallest effort possible, search for the standardization document that gave rise to it, then copy the implementation you'll find there. The document you want is N3656 by Stephan T. Lavavej, dated 2013-04-18. Just remember not to put your version in namespace std, because you won't want it to clash with a vendor-provided version when you upgrade to a C++14 Standard Library implementation.

std::make_uniqueand std::make_sharedare two of the three make functions : functions that take an arbitrary set of arguments, perfect-forward them to the constructor for a dynamically allocated object, and return a smart pointer to that object. The third makefunction is std::allocate_shared. It acts just like std::make_shared, except its first argument is an allocator object to be used for the dynamic memory allocation.

Even the most trivial comparison of smart pointer creation using and not using a makefunction reveals the first reason why using such functions is preferable. Consider:

auto upw1(std::make_unique< Widget>()); // with make func

std::unique_ptr< Widget> upw2(new Widget); // without make func

auto spw1(std::make_shared< Widget>()); // with make func

std::shared_ptr< Widget> spw2(new Widget); // without make func

I've highlighted the essential difference: the versions using newrepeat the type being created, but the makefunctions don't. Repeating types runs afoul of a key tenet of software engineering: code duplication should be avoided. Duplication in source code increases compilation times, can lead to bloated object code, and generally renders a code base more difficult to work with. It often evolves into inconsistent code, and inconsistency in a code base often leads to bugs. Besides, typing something twice takes more effort than typing it once, and who's not a fan of reducing their typing burden?

The second reason to prefer makefunctions has to do with exception safety. Suppose we have a function to process a Widgetin accord with some priority:

void processWidget(std::shared_ptr spw, int priority);

Passing the std::shared_ptrby value may look suspicious, but Item 41explains that if processWidgetalways makes a copy of the std::shared_ptr(e.g., by storing it in a data structure tracking Widgets that have been processed), this can be a reasonable design choice.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x