From: Howard Hinnant (hinnant_at_[hidden])
Date: 2002-02-05 14:59:15
On Tuesday, February 5, 2002, at 02:31 PM, Rainer Deyke wrote:
> There are three ways of dealing with this specific problem:
> 1. If any exceptions are thrown by the copy operation, catch it, move
> all elements back into their original position, and rethrow.
> 2. Copy 'x' first, then move the elements, then move the copy of 'x'
> into place.
> 3. push_back 'x' and use 'std::swap' to fix the order of the vector
> elements. This requires no move operation.
Yes, these will all work. And they are all less efficient than moving
elements out of the way once (directly to where they belong), leaving
valid elements in their place and copying x directly into place.
#1 generates significantly larger code size, and is harder to maintain.
#2 requires an extra buffer to move x into. And it requires twice the
computation to move x around twice. T could be a very lightweight class
with move semantics such as auto_ptr. (yes auto_ptr or something like it
could go into vector if it didn't pretend to copy when it moved).
#3 moves x around 3 times: once to the end and twice more during the
Why should we create a sub-optimal design? vector is to C++ like malloc
is to C. Everybody and their dog uses it to death. vector must be rock
solid and as efficient as possible in code size, performance, and memory
usage. And the whole point of move is optimization. If we can't create
a move that would be optimally useful to vector, then I believe we have
wasted our time.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk