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

前端 未结 19 1615
北恋
北恋 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:04

    If you work with data that doesn't need construction/destruction and requires reallocations (e.g., a large array of ints), then I believe malloc/free is a good choice as it gives you realloc, which is way faster than new-memcpy-delete (it is on my Linux box, but I guess this may be platform dependent). If you work with C++ objects that are not POD and require construction/destruction, then you must use the new and delete operators.

    Anyway, I don't see why you shouldn't use both (provided that you free your malloced memory and delete objects allocated with new) if can take advantage of the speed boost (sometimes a significant one, if you're reallocing large arrays of POD) that realloc can give you.

    Unless you need it though, you should stick to new/delete in C++.

提交回复
热议问题