Suppose I hace a class Student with the method:
Student Student::method(Student x)
{
//nothing important
return x;
}
The copy constructor is called twice, once when the object x is send as a parameter and second when x is returned from the function.
Why and when is the destructor for class Student called twice when I call this method?
The call is like this: a = b.method(c), where a, b and c are Student objects.
For your example,
a = b.method(c);, there are three copies that may take place, save for copy elision. The first is when thecobject is copied into the function parameterx. The second is when thexobject is returned from the function. The third is when the return value is copied into theaobject. The first two involve the copy constructor and the last involves the copy assignment operator, unless you change it toStudent a = b.method(c);, in which case they all use the copy constructor.a,b, andcwill all be destroyed at the end of their scope. The objectxwill be destroyed at the end of themethodfunction. The return value of the function will be destroyed at the end of the full expression that contains it – that is, oncea = b.method(c);has finished.However, not all of these copies must occur – the compiler is allowed to elide or omit the copy/move construction of a class under certain situations. The first copy into the function parameter will occur. The second copy out of the function will be treated as a move first, before attempting to copy it. This copy or move may be elided. The final copy, from temporary return value to
a, will occur if you’re using copy assignment, but may be elided if you use the copy constructor (as inStudent a = b.method(c);).