In what cases do I use malloc and/or new?

前端 未结 19 1680
北恋
北恋 2020-11-21 17:41

I see in C++ there are multiple ways to allocate and free data and I understand that when you call malloc you should call free and when you use the

19条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 18:02

    There are a few things which new does that malloc doesn’t:

    1. new constructs the object by calling the constructor of that object
    2. new doesn’t require typecasting of allocated memory.
    3. It doesn’t require an amount of memory to be allocated, rather it requires a number of objects to be constructed.

    So, if you use malloc, then you need to do above things explicitly, which is not always practical. Additionally, new can be overloaded but malloc can’t be.

提交回复
热议问题