First of all I'd like to understand why I get lines (5) and (6) in the output and not only one of them.
Second, why mc1.print()
prints valid values? Shouldn't _ms
point to undefined place after mc1(&MyStruct(mc2))
because the place where MyStruct was created (in cast operator) was already unwind?
struct MyStruct
{
int w;
int h;
MyStruct()
{
cout << "MyStruct" << endl;
}
~MyStruct()
{
cout << "~MyStruct: w=" << w << "h=" << h << endl;;
}
};
class MyClass1
{
public:
MyClass1(MyStruct* ms)
:_ms(ms)
{
cout << "MyClass1" << endl;;
}
~MyClass1()
{
cout << "~MyClass1" << endl;
}
void print()
{
cout << "print: w=" << _ms->w << "h=" << _ms->h << endl;
}
MyStruct* _ms;
};
class MyClass2
{
public:
MyClass2()
{
cout << "MyClass2" << endl;
}
~MyClass2()
{
cout << "~MyClass2" << endl;
}
operator MyStruct()
{
MyStruct ms;
ms.h = 11;
ms.w = 22;;
return ms;
}
};
int main()
{
MyClass2 mc2;
MyClass1 mc1(&MyStruct(mc2));
mc1.print();
return 0;
}
the output is
1. MyClass2
2. MyStruct
3. ~MyStruct: w=22h=11
4. MyClass1
5. ~MyStruct: w=22h=11
6. ~MyStruct: w=22h=11
7. print: w=22h=11