Is it safe to realloc memory allocated with new?

前端 未结 9 705
孤街浪徒
孤街浪徒 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:43

    In general, don't do that. If you are using user defined types with non-trivial initialization, in case of reallocation-copy-freeing, the destructor of your objects won't get called by realloc. The copy constructor won't be called too, when copying. This may lead to undefined behavior due to an incorrect use of object lifetime (see C++ Standard §3.8 Object lifetime, [basic.life]).

    1 The lifetime of an object is a runtime property of the object. An object is said to have non-trivial initialization if it is of a class or aggregate type and it or one of its members is initialized by a constructor other than a trivial default constructor. [ Note: initialization by a trivial copy/move constructor is non-trivial initialization. —end note ]

    The lifetime of an object of type T begins when:

    — storage with the proper alignment and size for type T is obtained, and

    — if the object has non-trivial initialization, its initialization is complete.

    The lifetime of an object of type T ends when:

    — if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or

    — the storage which the object occupies is reused or released.

    And later (emphasis mine):

    3 The properties ascribed to objects throughout this International Standard apply for a given object only during its lifetime.

    So, you really don't want to use an object out of its lifetime.

提交回复
热议问题