12

Possible Duplicate:
How are C array members handled in copy control functions?

If I don't override the operator = of a class, it will use default memberwise assignment.

But what does it mean?

struct A {
    int array[100];
};
A a;
A b=a;

No error. How does b copes a'sarray? Normally array_b = array_a is invalid.

Another exampe:

struct A {
    vector<int> vec;
};
A a;
A b=a;

How does b copes a'svec? Through assignment(vec_b = vec_a), constructor(vec_b = vector<int>(vec_a)) or other mystery way?

Community
  • 1
  • 1
Lai Yu-Hsuan
  • 27,509
  • 28
  • 97
  • 164
  • possible duplicate of http://stackoverflow.com/questions/4164279/how-are-c-array-members-handled-in-copy-control-functions – Invictus May 05 '12 at 12:14

2 Answers2

9
A b=a;

Is not assignment, it is called as Copy Initialization.

The implicitly generated copy constructor is called to create an new object b from the existing object a.
The implicitly generated copy constructor makes a copy of the array member.

For completeness I am going to add here the standard citation from the marked duplicate.

C++03 Standard: 12.8 (Copying class objects)

Each subobject is copied in the manner appropriate to its type:

  • if the subobject is of class type, the copy constructor for the class is used;
  • if the subobject is an array, each element is copied, in the manner appropriate to the element type;
  • if the subobject is of scalar type, the built-in assignment operator is used.
Alok Save
  • 202,538
  • 53
  • 430
  • 533
1

If the members have copy constructors, they get invoked. If not, the default copy constructor does the equivalent of memcpy. See Memberwise Assignment and Initialization.

In the case of non-pointer arrays, each element is copied.

Mr Fooz
  • 109,094
  • 6
  • 73
  • 101