8

Possible Duplicate:
Can I get a fresh start in C++ without failing again?

Consider T* o = new(T()), where T has a copy constructor defined. Also suppose expression new uses the default ::operator new()

To re-use the memory allocated for o, instead of deleting the object with delete o, does the standard allow the following sequence: 

  1. call o->~T() explicitly
  2. use placement new for creating a copy of an object on the memory allocated for o previously: new(o) T(x)
  3. when done with o and its memory, delete it with the delete o

I also ask this because I don't understand why std::map<T, V> (or its operator[] specifically), for example, requires T to have an appropriate assignment operator defined, if the above sequence could work without this requirement. I doubt that map has been designed this way just because operator=() and the copy constructor can have different semantics, since most of the time they are just implemented the same way.

Community
  • 1
  • 1
Martin
  • 9,089
  • 11
  • 52
  • 87
  • 1
    Exception safety is the answer to your `map` question. – Xeo Feb 06 '12 at 04:57
  • @Xeo Can you elaborate your answer? – Martin Feb 06 '12 at 05:10
  • 1
    If you do this and the constructor fails (in step 2), the existing object is already gone. A similar situation was discussed [here](http://stackoverflow.com/questions/8829548/can-i-get-a-fresh-start-in-c-without-failing-again). – R. Martinho Fernandes Feb 06 '12 at 05:12
  • @Martinho In my case the object is not allocated on the stack, so I know whether it is safe to delete it or not in step 3. – Martin Feb 06 '12 at 05:27
  • @Martin: remember that step 3 can happen long after this operation: in a map, that happens when the map is destroyed. Unless you want the failed construction of a new element to result in removal of existing ones. – R. Martinho Fernandes Feb 06 '12 at 05:30

0 Answers0