简体   繁体   中英

Usage of Global variables in C++

I am working on an application that reads files from an input directory,processes them and loads them on to DB. The two classes Filelist and CurrentFile are part of the application. The class defintions are as below.

class Filelist
{

   //list of files
   list of files;

   // pointer to the current file
   CurrentFile *ptr
};

class CurrentFile
{

   vector<list of records>

   methods to process the records
   ..
   ..
};

I have to add another Audit structure that keeps track of successfully processed records and errored out records. This audit structure gets loaded into the DB after all the files are processed.

struct Recaudit
{
     //record to keep track of
     //Various counts
     int successcnt;
     int errorcnt;
     billedcnt;
     some other counts related to the records
};

This audit record has its data set across multiple methods of CurrentFile.

Can this audit record be made a member variable of CurrentFile (or) should I declare it as a static global variable?

I guess, that Audit is some kind of log? You have to make a decision about its purpose.

  • If it's a general purpose log with an option to store information about import statuses, it shall be made a singleton (a "safe" kind of global variable). It's consistent with OOP rules, yet the class is easily available for all interested parties.
  • If it's designed specifically for storing information about import statuses, it has to be available for object performing the calculations, but shall be stored one level above (eg. in object containing list of all calculation objects). In your case the FileList should be a parent for the Audit (eg. it should maintain its lifetime), but CurrentFile should get an instance of Audit in the constructor, such that it can store results of the calculation within. In both cases be cautious about the multitasking, if you plan to implement one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM