tags:

views:

56

answers:

1

Who can give me a link for the operator= of vector in MSDN?

Why I can only find operator[]?

If operator= is just something default, like copy everything in A to B, how this following code works?

vector<double> v(100,1);
v = vector<double>(200,2);   // if operator= is just a trivail version, how to make sure the old v get cleared? 
+2  A: 

std::vector is part of the STL, so any description of std::vector will do. The underlying implementation may differ slightly, but all conformant versions of STL must provide the same interface and the same guarantees for std::vector. I can't find in quickly on MSDN, but here are two such descriptions of operator=:

  1. http://www.cplusplus.com/reference/stl/vector/operator=/
  2. http://www.sgi.com/tech/stl/Vector.html

Now, the second part of your question puzzles me. What would you expect operator= to do on a vector if not "copy everything from A into B"?

In your example, your question was "how to make sure the old v get cleared?". I can interpret this in one of two ways: You might be asking "how do I know that this assignment v = vector<double>(200,2) will overwrite the contents of v and not append to it?". The answer is that you know that because that's the definition of how operator= works for STL containers. Any standards compliant implementation is guaranteed to work that way.

You might also be asking "what happens to the contents of v when I overwrite them using the assignment v = vector<double>(200,2)?" The answer is that they are deallocated, and if they are objects, their destructors are called. Note the important distinction that if the vector contains pointers to objects, the pointers themselves are deallocated, but not what they point to.

If I didn't answer your question, please try to clarify it.

Tyler McHenry
My question is more like your second interpret.You said "The answer is that they are deallocated", but HOW if you just have a operator= COPYING every member in B.member to A.member without explicitly deallocating old A.member.
8888q8888
@8888: Who says it just copies every member?
GMan
8888q8888
@8888: That's exactly what there is. (Well, different function type.)
GMan
right, nobody said it just copies. The fact that I didn't find it in MSDN(2003~2008) leads me to think that way.
8888q8888
@8888: All documentation is bound to have errors, and consulting a second (and third) source is always a good idea. If all else fails, the source for `std::vector::operator=` is in `<vector>`; you can open it up and take a look.
James McNellis
Thank you all for your answers and suggestions!
8888q8888