2

For example if we had a 10 element vector, and we decided to erase the 5th element, all elements after the 5th would have to be moved back one element. Why is the assignment operator used here? Why not just copy the bits since we know the old copy is about to be overwritten / invalidated?

Obviously this changed we the move constructor. Let's just assume a move constructor / assignment isn't used here.

Ben
  • 1,816
  • 1
  • 20
  • 29
  • Can you show the code which uses the assignment operator here? Your question isn't very clear as it is now... – hyde Mar 30 '14 at 17:04
  • 3
    Because if simply copying bits was always appropriate, there'd be no need for assignment operator overloads. – Oliver Charlesworth Mar 30 '14 at 17:05
  • @hyde: it's buried in the standard libraries for each implementation, but it's either in or called from `std::vector::erase`. – Steve Jessop Mar 30 '14 at 17:05
  • @OliCharlesworth But in this case we're really moving the data, since the old copy won't ever be referenced again. – Ben Mar 30 '14 at 17:06
  • 2
    what if you have some logic in function used (either copy ctor or assignment operator)? You would like it to be called. – 4pie0 Mar 30 '14 at 17:06
  • possible duplicate of [Making swap faster, easier to use and exception-safe](http://stackoverflow.com/questions/4875289/making-swap-faster-easier-to-use-and-exception-safe) – fredoverflow Mar 30 '14 at 17:13
  • The assignment operator may just copy all the bits - if that's appropriate for the element type. – Alan Stokes Mar 30 '14 at 17:16

1 Answers1

4

The fundamental reason is so that C++ objects can preserve class invariants involving the address of the object (or its sub-objects)

Therefore if the value of an object is to be established at a different address the class might need to execute code to preserve the invariant. That code goes in the move/copy constructor/assignment and the swap function if applicable.

A (possibly over-elaborate) example of such an invariant is, "exactly one sub-object is registered with some global collection of pointers, but which one varies between objects". If all you do is copy the bits, then there's no opportunity to update the global collection with the "right" sub-object according to the object state.

There is a serious limitation in C++03, that there are classes for which it is appropriate to just copy all the bits in the case you describe, but where it is not appropriate to just copy all the bits for a copy assignment in general, and a copy is unnecessarily expensive in your case. That limitation is what C++11 move semantics address, giving the class the chance to behave differently.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699