Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

dialog box

Status
Not open for further replies.

BaharPamuk

Programmer
Jan 30, 2006
16
TR
Hi,

I want to create a variable such that it will preserve its value even if the program terminates. I mean it will stay in memory even if main() returns. How can i achieve this? Or is this possible?

Thanks.
 
Persistent int, for example:
Code:
class pint
{
  int val;
  string fname;
public:
  pint(const string& vname); //< External (file) image name.
  ~pint();
  operator int () const { return val; };
  operator int&() { return val; }
  pint& operator =(const int& x) { val = x; return *this; }
  bool save();
};

pint::pint(const string& vname):fname(vname)
{
  ifstream f(vname.c_str());
  if (f)
     f >> val;
  else
     val = 0;
};

pint::~pint()
{
  save();
}

bool pint::save()
{
  ofstream f(fname.c_str());
  bool ok = false;
  if (f)
     ok = true,f << val;
  return ok;
}
Now try repeat calls:
[/code]
int main(int argc, char* argv[])
{
pint x("persint");
cout << ++x << endl;
return 0;
}
[/code]
No explicit initialization for this class, of course.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top