Reference passed process vs value passed process

Can someone kindly explain each object's life cycle in each scenario I created in my code?

I cannot understand the output fully especially for scenario 4.


#include <iostream>
using namespace std;
class A{
public:
A() { cout << "Constructor Called!" << endl; }
~A() { cout << "Destructor Called!" << endl; }
A(A&a) { cout << "Copy Called!" << endl; }
A& operator=(A&o) { cout << "Assignment Called!" << endl; return *this; }
};
A& nothing(A a) {return a;}

void main(void) {

A aa, bb;
bb = nothing(aa);*/
/* Scenario 1: A&nothing(A a)
Constructor Called!
Constructor Called!
Copy Called!
Destructor Called!
Assignment Called!
Destructor Called!
Destructor Called!

Scenario 2: A&nothing(A&a)
Constructor Called!
Constructor Called!
Assignment Called!
Destructor Called!
Destructor Called!

Scenario 3: A nothing(A&a)
Constructor Called!
Constructor Called!
Copy Called!
Assignment Called!
Destructor Called!
Destructor Called!
Destructor Called!

Scenario 4: A nothing(A a)
Constructor Called!
Constructor Called!
Copy Called!
Copy Called!
Destructor Called!
Assignment Called!
Destructor Called!
Destructor Called!
Destructor Called!
*/

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Scenario 1: A&nothing(A a)
Constructor Called! // aa is created
Constructor Called! // bb is created
Copy Called!        // a is created as a copy of aa
Destructor Called!  // a is destroyed
Assignment Called!  // a is assigned to bb (NOT SAFE! a HAS ALREADY BEEN DESTROYED)
Destructor Called!  // bb is destroyed
Destructor Called!  // aa is destroyed

// Scenario 2: A&nothing(A&a)
Constructor Called! // aa is created
Constructor Called! // bb is created
Assignment Called!  // aa is assigned to bb
Destructor Called!  // bb is destroyed
Destructor Called!  // aa is destroyed

// Scenario 3: A nothing(A&a)
Constructor Called! // aa is created
Constructor Called! // bb is created
Copy Called!        // The return value is created as a copy of aa (referred to by a)
Assignment Called!  // The return value is assigned to bb
Destructor Called!  // The return value is destroyed
Destructor Called!  // bb is destroyed
Destructor Called!  // aa is destroyed

// Scenario 4: A nothing(A a)
Constructor Called! // aa is created
Constructor Called! // bb is created
Copy Called!        // a is created as a copy of aa
Copy Called!        // The return value is created as a copy of a
Destructor Called!  // a is destroyed
Assignment Called!  // The return value is assigned to bb
Destructor Called!  // The return value is destroyed
Destructor Called!  // bb is destroyed
Destructor Called!  // aa is destroyed 
Topic archived. No new replies allowed.