Skip to Content
Hands-On Design Patterns with C++
book

Hands-On Design Patterns with C++

by Fedor G. Pikus
January 2019
Intermediate to advanced
512 pages
14h 5m
English
Packt Publishing
Content preview from Hands-On Design Patterns with C++

Swap and STL containers

Conceptually, swap is equivalent to the following operation:

template <typename T> void swap(T& x, T& y) {     T tmp(x);    x = y;    y = tmp;}

After the swap() is called, the contents of the x and y objects are swapped. This, however, is probably the worst possible way to actually implement swap. The first and most obvious problem with this implementation is that it copies both objects unnecessarily (it actually does three copy operations). The execution time of this operation is proportional to the size of the T type. For an STL container, the size would refer to the size of the actual container, not to the type of the element:

void swap(std::vector<int>& x, std::vector<int>& y) {    std::vector<int> tmp(x);    x = y; y = tmp; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Structural Design Patterns in Modern C++

Structural Design Patterns in Modern C++

Umar Lone

Publisher Resources

ISBN: 9781788832564Supplemental Content