I have an ErrorLog
class, that is used to write and modify log files. I'd like to write to it before and after major events for debugging purpo开发者_如何学运维ses and I only want to use one instance of the ErrorLog
class for the entire application. I tried declaring an ErrorLog
object as a global by placing
ErrorLog exe_log;
into a header file so it is accessbile to other files, but I keep getting an error saying it is already defined. Is there a correct way to defing global objects?You need a declaration in a header file and a definition in a source file.
foo.h:
extern ErrorLog exe_log; // declaration (note the "extern")
foo.cpp:
ErrorLog exe_log; // definition
bar.cpp:
#include "foo.h"
You should define it like that in a single source file, and declare it in a header as:
extern ErrorLog exe_log;
Having said that, using global variables or class instances is frowned upon. You should get in the habit of trying to avoid that as much as possible.
A design pattern known as Singleton has been proposed to deal with such cases, although nowadays many developers, for good reasons, highly discourage its use.
I don't know about any "correct" way (at least, the standard doesn't define one afaik). However, one good way to use global objects is to define them using the singleton pattern. In your case, this would translate to declaring a static member in your ErrorLog class with the type of ErrorLog. This way, the global object will not be in the global scope (which can be dangerous in some cases).
I think you are looking for the Singleton Pattern. You should have a static member of the type ErrorLog*
in your ErrorLog
class and initialise it with a create function, similar to this:
// .h file
class ErrorLog {
public:
static ErrorLog* create() {
if (!this->log)
this->log = new ErrorLog();
return this->log;
}
private:
static ErrorLog* log;
ErrorLog() {}
}
// .cpp file
ErrorLog* ErrorLog::log = NULL;
精彩评论