I think I understand the basic ideas behind pass-by-value and pass-by-reference. I have created a toy code to explain my question:
class C2 {
public:
int val;
C2() {}
~C2() {}
};
class C1 {
public:
C2 * x;
C1(C2 & x_) {
x = &x_;
}
C1() {}
~C1() {}
};
void func (C1 & y) {
C2 z;
z.val = 5;
y = C1(z);
}
void func_p (C1 & y) {
C2 * z;
z = new C2();
z->val = 5;
y = C1(*z);
delete z;
}
int main()
{
C1 m_y1;
func(m_y1);
cout << m_y1.x->val << endl; // Prints 5
C1 m_y2;
func_p(m_y2);
cout << m_y1.x->val << endl; // Prints junk instead of seg fault
return 0;
}
I had the following questions:
- How can the first cout print 5. Object
z
is local tofunc
, and would go out of scope after func is exited. So accessing a pointer pointing toz
(in this casex
inC1
) should have resulted in a segmentation fault? - The second cout prints junk (32766 or so). Since
z
is deleted infunc_p
shouldn't this also result in segmentation fault?
Edit:
Thank you (I will delete this question since it was flagged for duplicate and I can understand why it is duplicate. I just got entagnled with these reference passes!)
Just to clarify my understanding, please consider func_c
void func_c (C2 & y) {
C2 z;
z.val = 5;
y = z;
}
int main()
{
C1 a;
a.x = new C2();
func_c(*(a.x));
cout << a.x->val << endl; // Prints 5
}
I am assuming this will be a defined behavior because the copy function will be called. Initially a.x = new C2()
, and after func
is called, z
object is copied into a.x
?