Difference between operator new() and operator new[]()?

后端 未结 5 666
礼貌的吻别
礼貌的吻别 2021-01-04 19:40

Is there any difference between fncs: operator new and operator new[] (NOT new and new[] operators)? Except of course call syntax? I\'m asking because I can allocate X numbe

5条回答
  •  旧时难觅i
    2021-01-04 20:25

    Allocation is one thing, object construction/destruction is another.

    A new performs one allocation and one construction. However, a new[] still allocates one continuous memory block, but calls many constructors.

    The situation is the same with delete and delete[].

    BTW- I'm not 100% sure with what I'm about to say, but I believe that you won't get an imemdiate memory leak if you call delete on an address received from new[]. The whole memory block would probably be freed. However, this is invalid because you'd call the destructor on the first object only, instead of on every object in the array. And this may result in secondary memory leaks... and lots of logic errors due to broken 1-1 relation of constructors and destructors, of course.

    (Also, remember to consider using boost::array or std::vector instead of new[]! :))

提交回复
热议问题