Reputation: 12237
I get an error stack around variable dlgFile is corrupted
which I am trying to fix. This is legacy code and it looks dubious. I replaced part of in another project which is here:
void CPlantDlg::OnBnClickedButtonTestReference()
{
CString str = _T("Hello string");
{ // intentional so destructor of Tester is called below
Tester tester( str );
}
AfxMessageBox (str );
}
The Tester class is:
class Tester
{
public:
Tester(CString & str);
~Tester(void);
CString _str;
};
Tester::Tester(CString & str) : _str( str )
{
}
Tester::~Tester(void)
{
//_str = "Changed"; // say I do this, what will be printed in caller function?
}
Is passing of the CString safe this way? I think the Tester
class should destroy its _str
which should result in getting the original str destroyed outside the class?
When I run it does prompt "Hello String" though.
If I enable _str = "Changed"
what will you expect to prompt? It actually still shows the original string. It was passed by reference, why is that?
Upvotes: 0
Views: 89
Reputation: 428
The _str variable in your Tester class is an instance of a CString object. When the member initializer says
_str( str )
it is not storing a reference to the CString reference that is passed to the constructor, the copy constructor is being called, and _str is initialized with the same value as str. It is just a copy. So changing it will not have an effect on the original CString.
Upvotes: 3