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?
CodePudding user response:
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
.