if i have a vector and assign another vector to a vector variable like this:
vector<int> c, k;
c.push_back(1), c.push_back(2);
k.push_back(3), k.push_back(4);
c = k;
does this work??
Depends on what you want.
if it does, i assume a copy of k is made and assigned to c.
This is not a "copy" but an assignment. In particular, the assigment
operator is called for the object c. That's different from the copy
constructor.
std::vector<int> c = k;
std::vector<int> c(k);
These two both use the copy constructor and
std::vector<int> c;
c = k;
this one uses the assignment operator. Basically, both the copy ctor
and the assignement operator do the same thing in the sense that they
copy the elements in k, except that the copy ctor works on a not yet
constructed object and the assignment operator is called on an already
created object. That means the assignment operator must make sure
memory (in particular) is correctly managed.
will the memory occupied by the original c-vector be reclaimed?
(This is implementation-defined. It depends on the library you are
using. My answer is based on a common implementation.)
It depends. Vectors keep, among others, two very important variables :
1. the total amount of memory allocated
2. the total amount of memory used
Vectors usually allocate more memory than they need and then keep some
info to know how many elements there are. That means if you do
c = k;
if 'k' uses more memory than 'c' has allocated (for example, k has 25
elements, but c only has memory for 10), 'c' will need to allocate some
more. That means
1. allocating enough to store k's elements
2. copying k's elements
3. deleting the old memory
So in that case, yes, the memory will be deleted ("reclaimed"). If 'c'
has enough memory allocated to accomodate all of k's elements, it does
not need more and therefore doesn't touch the buffer.
The most important thing to remember here is that you (usually) don't
need (or want) to know the internals of the standard library. Get a
good book describing the behaviors of the library (such as Josuttis') so
you know how to use its features, but refrain from wanting to learn
_how_ something works. First, that's not relevant and second, it
probably won't work the same on another compiler.
Jonathan