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

Deallocating std::list without going out of scope

In STL one of the ways to create a dynamically allocated array is to create a list. When lists go out of scope destructor for every element is called and the list is deleted. Is there a way to destroy list (and more importantly release the memory used) before list going out of scope, and if it’s possible then what is the best way to do it? Will delete[] or list::clear() do the job?

>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

In STL one of the ways to create a dynamically allocated array is to create a list.

Linked lists and arrays are quite different data structures.

Is there a way to destroy list (and more importantly release the memory used) before list going out of scope

You can erase all elements of std::list, or any other standard container (excluding std::array) using the clear member function. All standard containers except for std::vector and std::basic_string release the memory allocated for elements when they are erased in practice. You may achieve the same with vector and string using shrink_to_fit after clearing.

Alternatively, it may be a good idea to make the scope of the list smaller instead.

Will delete[] … do the job?

No. delete[] may be used only with pointers to first element of array created using an allocating new-expression. std::list is not a pointer created using an allocating new-expression. You may not use delete[] on a std::list.

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