Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does delete delete every element in a vector and free the memory?

    vector<int>* v = new vector<int>;
    for (int i = 0; i < 100; i++) {
        (*v).push_back(i);
    }
    delete v;

Do I delete every element of the vector and free the memory? If not how do I free the memory?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

An allocating new expression allocates memory, constructs a dynamic object into that memory, and returns a pointer to that object. When you pass such pointer to delete, the pointed object is destroyed and the memory is deallocated.

When an instance of a class, such as a vector is destroyed, its destructor is called. The destructor of vector destroys all elements of the vector.


Sidenote 1: It’s rarely useful to use allocating new and delete. When you need dynamic storage, prefer to use RAII constructs such as containers and smart pointers instead.

Sidenote 2: You should avoid unnecessary use of dynamic memory in general. It’s quite rare to need singular dynamic vector such as in your example. I recommend following instead:

std::vector<int> v(100);
std::ranges::iota(v, 0);

Sidenote 3: Avoid using (*v).push_back. It’s hard to read. Prefer using the indirecting member access operator aka the arrow operator instead: v->push_back

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading