Search code examples
vectordynamic-memory-allocationnew-operator

What are the differences between using vector and using new,delete in c++?


I would like to ask about the difference between using vector and using new, delete in C++. Both new, delete and malloc, free are used for dynamic memory allocation.

So why don't we just use vector, which automatically allocates memory for us in C++?

Under what circumstances would we need to manually allocate memory using new, delete instead of directly using vector?

I'd appreciate some guidance on this matter. Thank you.

Or perhaps I have misunderstood something.


Solution

  • In environments with strict performance and memory constraints, such as embedded systems, manual memory management using new and delete offers precise control over memory allocation. Unlike std::vector, which dynamically adjusts memory size and could potentially exhaust available memory with a simple call to push_back, new and delete provide deterministic memory usage.

    Also, this is crucial in time-sensitive applications where every millisecond counts. Another thing, in C-based ecosystems like the Linux kernel and modules, where std::vector isn't available, new and delete remain indispensable for efficient memory utilization. Despite the convenience of std::vector, in contexts demanding tight resource management and optimal performance, the direct control provided by new and delete proves invaluable.