Malloc vs New for Primitives

I understand the benefits of using new against malloc in C++. But for specific cases such as primitive data types (non array) - int , float etc., is it faster to use malloc than new ?

Although, it is always advisable to use new even for primitives, if we are allocating an array so that we can use delete[] .

But for non-array allocation, I think there wouldn't be any constructor call for int ? Since, new operator allocates memory, checks if it's allocated and then calls the constructor. But just for primitives non-array heap allocation, is it better to use malloc than new ?

Please advise.


Never use malloc in C++. Never use new unless you are implementing a low-level memory management primitive.

The recommendation is:

  • Ask yourself: "do I need dynamic memory allocation?". A lot of times you might not need it - prefer values to pointers and try to use the stack.

  • If you do need dynamic memory allocation, ask yourself "who will own the allocated memory/object?".

  • If you only need a single owner (which is very likely), you should use std::unique_ptr . It is a zero cost abstraction over new / delete . (A different deallocator can be specified.)

  • If you need shared ownership, you should use std::shared_ptr . This is not a zero cost abstraction, as it uses atomic operations and an extra "control block" to keep track of all the owners.


  • If you are dealing with arrays in particular, the Standard Library provides two powerful and safe abstractions that do not require any manual memory management:

  • std::array<T, N> : a fixed array of N elements of type T .

  • std::vector<T> : a resizable array of elements of type T .

  • std::array and std::vector should cover 99% of your "array needs".


    One more important thing: the Standard Library provides the std::make_unique and std::make_shared which should always be used to create smart pointer instances. There are a few good reasons:

  • Shorter - no need to repeat the T (eg std::unique_ptr<T>{new T} ), no need to use new .

  • More exception safe. They prevent a potential memory leak caused by the lack of a well-defined order of evaluation in function calls. Eg

    f(std::shared_ptr<int>(new int(42)), g())
    

    Could be evaluated in this order:

  • new int(42)
  • g()
  • ...
  • If g() throws, the int is leaked.

  • More efficient (in terms of run-time speed). This only applies to std::make_shared - using it instead of std::shared_ptr directly allows the implementation to perform a single allocation both for the object and for the control block.

  • You can find more information in this question.


    It can still be necessary to use malloc and free in C++ when you are interacting with APIs specified using plain C, because it is not guaranteed to be safe to use free to deallocate memory allocated with operator new (which is ultimately what all of the managed memory classes use), nor to use operator delete to deallocate memory allocated with malloc .

    A typical example is POSIX getline (not to be confused with std::getline ): it takes a pointer to a char * variable; that variable must point to a block of memory allocated with malloc (or it can be NULL, in which case getline will call malloc for you); when you are done calling getline you are expected to call free on that variable.

    Similarly, if you are writing a library, it can make sense to use C++ internally but define an extern "C" API for your external callers, because that gives you better binary interface stability and cross-language interoperability. And if you return heap-allocated POD objects to your callers, you might want to let them deallocate those objects with free ; they can't necessarily use delete , and making them call YourLibraryFree when there are no destructor-type operations needed is unergonomic.

    It can also still be necessary to use malloc when implementing resizable container objects, because there is no equivalent of realloc for operator new .

    But as the other answers say, when you don't have this kind of interface constraint tying your hands, use one of the managed memory classes instead.


    It's always better to use new . If you use malloc you still have to check manually if space is allocated.

    In modern c++ you can use smart pointers. With make_unique and make_shared you never call new explicitly. std::unique_ptr is not bigger than the underlying pointer and the overhead of using it is minimal.

    链接地址: http://www.djcxy.com/p/13758.html

    上一篇: 为什么使用'new'导致内存泄漏?

    下一篇: 马洛克vs新的原始人