Hacker News new | ask | show | jobs
by NaNDude 1230 days ago
the most important point to keep in mind is the default pass by value context.

without defining a copy constructor, the compiler will do the copy himself, the point is : there is no copy constructor to call, so you have :

1) first the new Complex c3 is allocated,

2) there is no copy constructor to call

3) the compiler do the job, the memory used by c2 is copied on c3.

end of the story, no parameter value.

when adding a legal copy constructor (pass by reference), you may consider the reference like some sort of pointer. this is false, but help to understand the memory behavior of a copy constructor. then you have something like :

1) first the new Complex c3 is allocated

2) the "memory" for c, the reference/pointer to c2, is allocated.

3) the _address_ of c2 is copied in c.

4) the c3 constructor start with the reference/pointer/address of c2 as parameter.

end of the story, normal "pass by value" of an address.

finaly, if a copy constructor _without_ reference/pointer was legal, you will have:

1) first the new Complex c3 is allocated,

2) another new Complex, the c3 copy constructor parameter value c, is allocated.

3) instead of directly copying c2 memory to c, there is the c copy constructor to call (with a copy of c2 as parameter value)

4) another new Complex c_bis, the c copy constructor parameter value (c), is allocated.

5) instead of directly copying c2 memory to c_bis there is the c_bis copy constructor to call (with a copy of c2 as parameter value)

6) another new Complex c_bis_bis is allocated ... etc.

the problem is that a copy constructor is _implicitly_ called to create a copy, which transform a pass by value semantic in an infinite loop of allocations on the stack.

hope this help.

1 comments

"complex (complex c)" does it calls itself?
implicitly yes.