Is it safe to realloc memory allocated with new?

前端 未结 9 702
孤街浪徒
孤街浪徒 2020-12-02 17:12

From what is written here, new allocates in free store while malloc uses heap and the two terms often mean the same thing.

<
9条回答
  •  没有蜡笔的小新
    2020-12-02 17:55

    In general, no.

    There are a slew of things which must hold to make it safe:

    1. Bitwise copying the type and abandoning the source must be safe.
    2. The destructor must be trivial, or you must in-place-destruct the elements you want to deallocate.
    3. Either the constructor is trivial, or you must in-place-construct the new elements.

    Trivial types satisfy the above requirements.

    In addition:

    1. The new[]-function must pass the request on to malloc without any change, nor do any bookkeeping on the side. You can force this by replacing global new[] and delete[], or the ones in the respective classes.
    2. The compiler must not ask for more memory in order to save the number of elements allocated, or anything else.
      There is no way to force that, though a compiler shouldn't save such information if the type has a trivial destructor as a matter of Quality of Implementation.

提交回复
热议问题