Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually performing memory reallocation in c++ vectors

Tags:

c++

memory

vector

From this link, it says that there are four steps for memory reallocation when using c++ vectors...

  1. Allocate enough memory for the desired new capacity;
  2. Copy the elements from the old memory to the new;
  3. Destroy the elements in the old memory;
  4. and Deallocate the old memory.

I am particularly interested in numbers 3 and 4, is it possible to perform these tasks through code? Or does it just happen in the background.

I.e., am I able to "Destroy elements in memory" through code in C++? And am I able to directly "Deallocate memory" in C++ code?

like image 940
Ogen Avatar asked Nov 17 '25 08:11

Ogen


2 Answers

Yes, and yes! You might want to look into either the std::allocator type, or into placement new, operator new, destructor calls, and operator delete. (Note that operator new and operator delete are names of allocation and deallocation functions and not the same as the new and delete operators).

Hope this helps!

like image 150
templatetypedef Avatar answered Nov 19 '25 21:11

templatetypedef


am I able to "Destroy elements in memory" through code in C++?

Yes. By calling the object's destructor. For example, if x is a reference to an object of type T, you can destroy that object with:

x.~T();

And am I able to directly "Deallocate memory" in C++ code?

Of course. There are a variety of deallocation functions, that go with corresponding allocation functions. If you allocated with malloc, you deallocate with free. If you allocated with operator new(), you deallocate with operator delete(). If you allocated with new char[], you deallocate with delete[].

like image 37
Benjamin Lindley Avatar answered Nov 19 '25 22:11

Benjamin Lindley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!