-1

What is the difference between copy and assigning a vector ? line 2 and 4 .

1    vector<int> V1(5);
2    vector<int> V3(V1);
3    vector<int> V4(V1.size());   
4    V4 = V1 ;
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 4
    Copying creates a new vector. When assigning they both already exist. – Bo Persson Mar 08 '13 at 09:30
  • 1
    The same as for any other type with copy construction and assignment. BTW you do not need the third line. – juanchopanza Mar 08 '13 at 09:34
  • one calls the copy constructor, the other calls the `=` operator – default Mar 08 '13 at 09:43
  • possible duplicate: http://stackoverflow.com/q/11706040/238902 – default Mar 08 '13 at 09:45
  • 1
    One thing to keep in mind: If you use a type which is expensive to construct rather than a simple `int`, then the combination of line 3&4 will be more expensive as it will default-construct a lot of elements before chucking them away in favor of the copied objects. This does not happen in line 2. – us2012 Mar 08 '13 at 09:45
  • 1
    This question is very vague - the syntactical difference between the two is very clear, so you probably are asking about the semantical difference. In that case, please explain *why* you ask that question, so we can focus our answer on that. This is actually a rather complex topic. – Björn Pollex Mar 08 '13 at 13:38
  • Well, one is a construction, the other is an assignment. Apart form any practical difference regarding performance, cleanliness or whatever, there is a fundamental semantic difference between changing the value of an existing object and creating a new one. So you might want to clarify your question, stating in what difference you're interested, as in respect to what. – Christian Rau Mar 08 '13 at 13:40

2 Answers2

0

Here is a doxygen extract from my stl implementation for operator=:

   /* All the elements of @a x are copied, but any extra memory in
   *  @a x (for fast expansion) will not be copied.  Unlike the
   *  copy constructor, the allocator object is not copied.
   */

As you can see there is a difference if you use custom allocators, but in other cases the result is the same.

FredericS
  • 413
  • 4
  • 9
0

Line 2 uses a copy constructor. Line 4 uses a copy assignment. Both create copies; the first creates a new object and the second overwrites an existing object.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165