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

前端 未结 19 1621
北恋
北恋 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条回答
  •  抹茶落季
    2020-11-21 18:14

    To answer your question, you should know the difference between malloc and new. The difference is simple:

    malloc allocates memory, while new allocates memory AND calls the constructor of the object you're allocating memory for.

    So, unless you're restricted to C, you should never use malloc, especially when dealing with C++ objects. That would be a recipe for breaking your program.

    Also the difference between free and delete is quite the same. The difference is that delete will call the destructor of your object in addition to freeing memory.

提交回复
热议问题