Skip to main content
edited tags; edited title; edited tags
Link
200_success
  • 145.7k
  • 22
  • 191
  • 481

Monitoring errors with singleton - can it be done better?

Source Link
Tim
  • 111
  • 3

Monitoring errors with singleton - can it be done better?

I need to monitor my functions for "errors" and want to print the warnings at the end of the functions. I thought using singleton class could be a good idea in here (code inspired by this example):

class Warning { bool status; std::string message; static Warning *global_warning_ptr; Warning() { defaults(); } public: void defaults() { message = "no warnings"; status = false; } void set(std::string v) { message = v; status = true; } void print() { if (status) { std::cout << message std::endl; defaults(); } } static Warning *msg() { if (!global_warning_ptr) global_warning_ptr = new Warning; return global_warning_ptr; } }; Warning *Warning::global_warning_ptr; 

that is used by multiple functions as below

void bar(double x) { if (x < 0) Warning::msg()->set("Wrong values"); } void foo(std::vector x) { int n = x.size(); for (int i = 0; i < n; i++) { bar(x[i]); } Warning::msg()->print(); // print single warning if any error occures } 

However using singletons is often considered as a bad coding practice. Is there any better alternative or place for improvment in my code? Is there anything I should worry about when using it?