Monitoring errors with singleton 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 &lt;&lt; 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 &lt; 0)
    Warning::msg()-&gt;set("Wrong values");
}

void foo(std::vector x) {
  int n = x.size();

  for (int i = 0; i &lt; n; i++) {
    bar(x[i]);
  }

  Warning::msg()-&gt;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?
I don't want to sound harsh, but the code is useless. On top of that, the singleton seems to be slightly off in this situation. You should have a function which is a friend to the class and has static local variable and then simply return reference to it. The class itself should have private constructor, so that only the specified function can instantiate it.

Why?


Because it is not thread safe
Because it is singleton
Because only one message is supported at a time
No real way to retrieve the message as string (companies will need a person who looks at the monitor)
Memory leak


Alternative:

CustomStream&amp; debugStream()
{
    static CustomStream stream;
    return stream;
}


where CustomStream is thread safe stream possibly inhertied from std::ostream. Do note that static variables are initialized in a thread safe way only from C++11 and forward (there might be some compiler extensions that allow it prior to C++11).