clear() vs destructor?

L

Lambda

For a std::vector, what's the difference between
the clear() function and its destructor?

I know their usages are different,
but how about their implementations?
 
C

C C++ C++

For a std::vector, what's the difference between
the clear() function and its destructor?

I know their usages are different,
but how about their implementations?


clear is to clear the data but not the memory allocation.
destructor clears everything.
 
L

Lambda

clear is to clear the data but not the memory allocation.
destructor clears everything.

Do you mean:
1. If the vector has 100 elements
2. clear()
3. Then the 100 memory spaces are not released, and
all the 100 elements are uninitialized?
 
C

C C++ C++

Do you mean:
1. If the vector has 100 elements
2. clear()
3. Then the 100 memory spaces are not released, and
all the 100 elements are uninitialized?

It will release all 100 but keep the minimum memory space required for
vector.
 
C

C C++ C++

Do you mean:
1. If the vector has 100 elements
2. clear()
3. Then the 100 memory spaces are not released, and
all the 100 elements are uninitialized?

"Calling clear() removes all elements from the controlled sequence.
The memory allocated is not freed, however. All iterators become
invalid, of course." - from codeguru dot com c++ article number c4027
 
J

joseph cook

Not sure what the standard says but my implementation does not release
any memory.  I am pretty sure it is not required by the satandard to
release the memory.  I don't know if it is allowed but I don't think I
have noticed an implementation that shrink the vector capacity.  Each
elements of the vector will however be destructed correctly when
clear() is called.

In fact, the opposite is true. It is "required" that memory not be
released. (in so far at least that the capacity() of the vector before
and after a clear() will remain the same)

Joe Cook
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top