Link to home
Start Free TrialLog in
Avatar of VEngineer
VEngineer

asked on

global dialog object

Is it illegal to define a program-global dialog box object?  It compiles perfectly, but when I run it, it gives me a runtime debug assertion error.

This is a dialog based app so I have a main dialog class called CTheDlg which is run in a modal loop in CTheApp.
What I need to do is have access (inspect and change) to a data member in CTheDlg throughout the whole program.  Is there a better method?
Avatar of nietod
nietod

MFC is not my area of expertise, but the problem could be that the constructor for the global dialog object needs to use MFC elements that are not initialized.

The solution would be to use a global pointer to a dynamically allocated object.  Allocate the object at startup, after MFC is done initializing.
Why not try this:
CTheDlg * get_the_only_CTheDlg() {
  static CTheDlg dlg(...);
  return &dlg;
}

This will delay the initialization until the object is ready to be used and you will not have to explicitly call constructors and destructors.  I use this kind of thing a lot and have boilde it down to a template.

template<class T>T& get_the_only() {
  static T only_T;
  return only_T;
}

and then call it:

class CWhatever {
  public:
    CWhatever();

  public:
    func();
};





get_the_only<CWhatever>().func();

of course, this will only work if you have a constructor that takes no parameters.  This obviously will work without MFC.
oops, sorry.  I meant to make that a comment.
Avatar of VEngineer

ASKER

Ok.. it's a comment again.
Let me try some of these options and see which one works out.
My comment is complementary to nietod's.  I am agreeing with what he says, just giving an easier way to manage the memory.
ASKER CERTIFIED SOLUTION
Avatar of Priyesh
Priyesh

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
the only problem with a global dialog box (or any global object) is thread/concurrency.  If you have but one thread (most common case), this is not an issue.  

Thanks for the help.  I found a hybrid solution with everyone's comments.
use AfxGetMainWnd() instead of AfxGetApp()->m_pMainWnd