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

25 views Asked by At

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.

2

There are 2 answers

2
Mohamed Mahmoud On BEST ANSWER

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.

0
Caleth On

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

We do, the vast majority of the time. The small proportion of the time we aren't using vector, we are using some other container.

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

Never.