deallocating vector storage

T

Tino

In TC++PL (third edition), Section 16.3.8, Stroustrup gives the
following as a way to give memory from a std::vector back to the
system:

vector<int> tmp = v; // v.size() == 0
v.swap( tmp ); // v now has capacity of tmp (default), extra capacity
returned to system

We need to have a general method that returns memory back to the
system for vectors which are no longer needed, but have not yet gone
out of scope. Are there alternative suggestions for accomplishing
this?

Regards,
Ryan
 
V

Victor Bazarov

Tino said:
In TC++PL (third edition), Section 16.3.8, Stroustrup gives the
following as a way to give memory from a std::vector back to the
system:

vector<int> tmp = v; // v.size() == 0
v.swap( tmp ); // v now has capacity of tmp (default), extra capacity
returned to system

We need to have a general method that returns memory back to the
system for vectors which are no longer needed, but have not yet gone
out of scope. Are there alternative suggestions for accomplishing
this?

There is no guarantee that the storage will be returned. Swapping with
an empty vector, clearing the vector, resizing it to 0, all are good
attempts to accomplish what you need, but the Standard makes no promises
WRT the memory allocation behaviour. It's all platform-dependent and
implementation-dependent, I believe.

V
 
I

Ioannis Vranos

Tino said:
In TC++PL (third edition), Section 16.3.8, Stroustrup gives the
following as a way to give memory from a std::vector back to the
system:

vector<int> tmp = v; // v.size() == 0
v.swap( tmp ); // v now has capacity of tmp (default), extra capacity
returned to system



Why I do not see this in 16.3.8?



The above has no real effect (it exchanges emptiness) and no memory is
returned to the system.


We need to have a general method that returns memory back to the
system for vectors which are no longer needed, but have not yet gone
out of scope. Are there alternative suggestions for accomplishing
this?


Yes. The erase(), clear(), resize(), pop_back() member functions.






Regards,

Ioannis Vranos
 
I

Ioannis Vranos

Ioannis said:
Yes. The erase(), clear(), resize(), pop_back() member functions.



And if you mean to get rid of the container itself, you can make it on
the free store, however the whole thing sounds like a bad design. Why
you would not need a vector till the end of the scope? Perhaps the scope
is larger than it should.






Regards,

Ioannis Vranos
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top