The code you show does not reallocate memory if the container should not grow, which can be significant savings. Copy-and-swap always allocates memory for copying, and then frees memory for existing elements.
Consider a deque<vector<int>> , where existing vector deck elements have large capacities.
deque<vector<int>> d(2); d[0].reserve(100); d[1].reserve(100);
Using the SGI STL implementation, assigning to each element preserves this capacity, so if vectors need to grow, they can do this without allocating anything:
d = deque<vector<int>>(2); assert(d[0].capacity() >= 100); assert(d[1].capacity() >= 100); d[0].push_back(42);
Copy-and-swap will replace existing elements with new elements that do not have backup capacity, so the above statements will fail, and push_back will need to allocate memory. This takes time to free and redistribute, instead of using a perfectly good memory that already exists.
Copy-and-swap is a convenient way to get exceptional security and correctness very easily, but not necessarily as efficiently as possible. In code such as STL or the standard C ++ library, you don’t want to sacrifice efficiency for an easier implementation, and such code should usually be written by experts who can be eligible for exceptions, making it the “hard way” "not only the most convenient way.
source share