Thanks for that but it doesn't really answer the question, I will put a bit more of an explanation into it.
Lets say I have a CWindow object that represents a GUI window. The window has a caption property that is a CString, in this ficticious program the window's caption must remain the same as the path to a database, the path to the database would be stored in a CString as well, it would be good to only have one CString object and have both the window's caption and database path use it. The problem is shown below:
Code: Select all
// defined elsewhere
class CString;
class CWindow {
public:
...
void SetCaption( CString &sCaption ) {
m_pCaption = &sCaption;
}
private:
CString *m_pCaption;
};
CWindow MainWnd;
CString *pDBPath;
int main() { // <-- Just for you Schol-R-LEA ;)
pDBPath = new CString("Some Initial Path");
MainWnd.SetCaption( *pDBPath );
... Other Code ...
delete pDBPath;
... Other Code ...
return 0;
}
At the point of the second '... Other Code ...' m_pCaption in MainWnd points to nothing, if at anytime it tries to access it the program will crash, this is because assigning a value to a pointer does not invoke any member or friend functions so the original instance has no way to know that another pointer is referencing it, is adding an AddRef(); member function and calling it after referencing the object the only possible way to handle such a situation.
Code: Select all
class CWindow {
public:
...
void SetCaption( CString &sCaption ) {
m_pCaption = &sCaption;
sCaption.AddRef(); // is this my only solution??
}
private:
CString *m_pCaption;
};
I know that this is probably a reasonable solution, but I think it is ugly and prone to possible errors which defeat the purpose of reference counting anyway, the whole idea is to automatically release the resources, but only once the reference count is 0, one mistake of not adding the call to AddRef(); breaks the whole thing. >:(
Cheers.