I am trying to wrap my head about scope in C++. Please consider the following:
class C
{
int i_;
public:
C() { i_ = 0;}
C(int i) { i_ = i; }
C(const C &c) {
i_ = c.i_;
cout << "C is being copied: " << i_ << endl;
}
int getI() { return i_; }
~C() {cout << "dstr: " << i_ << endl;}
};
class D
{
C c_;
public:
void setC(C &c) { c_ = c; }
int getC_I() { return c_.getI(); }
};
void Test(D &d)
{
C c(1);
d.setC(c);
//here c is going out of scope, surely it will be destroyed now?
}
int main()
{
D d;
Test(d); //this sets value of c_ to the local variable in Test.
//Surely this will be invalid when Test returns?
int ii = d.getC_I();
cout << ii << endl;
}
Running this program outputs:
dstr: 1
1
dstr: 1
Apparently, the first destructor call occurs in Test, and the other when program terminates and d is destroyed.
So my question is: Where was c copied? Is there fault with my reasoning? And general point I am trying to ask: is it safe to have a member function that takes a reference to an object and then stores it in a member variable?
Many thank for your help.