C ++ for checking monophonic pointers

I have an application that has (Qt C ++) singleton logger class. Implementation of GetInstance ():

if(m_Instance == NULL)
{
    try
    {
        m_Instance = new Logger();
    }
    catch(...){}
}
return m_Instance;

Now I have the following macro in the .h file: "#define Log Logger :: Instance () → Log"

Everything is fine if a new () operation is running. What is the best way to make sure the pointer is set (I thought some try-catch blocks would catch std :: bad_alloc, but I don't know how to implement this in a macro)? I created a workaround that seems to work, but not very pretty:

"# define LOG if (Logger :: Instance ()) Logger :: Instance () → Log"

Also, I would like to know that if my object has many getters / setters (e.g. setPath (), getSize () ...)? I currently have a macro:

"# define SET Settings :: Instance ()"

SET- > setPath ( "abc" ); SET- > getSize();

, . , ?

.

+3
7

→ .

Logger& Logger::GetInstance() {
    static Logger instance; 
    return instance;
}

. .

+9

, , , , , ? - , , , .

(: ), , .

, , m_instance - boost:: scoped_ptr, ( ). , , , , , .

, , , . :

void write_to_log(Logger* logger, const char* msg)
{
    if (logger)
        logger->log(msg);
}

:

void write_to_log(const char* msg)
{
    Logger* logger = Logger::instance();
    if (logger)
        logger->log(msg);
}
+3

, , .

, , , , .

, , , .

+2

(, , ), :

struct ILogger {
    void Log(const char *message) = 0;
};

struct NullLogger : ILogger {
    void Log(const char *message) { }
};

struct Logger : ILogger {
private:
    static ILogger *m_instance;
    static const NullLogger m_null_instance;

public:
    void Log(const char *message) { /* ... */ }

    static ILogger *Instance() {
        if(m_Instance != &m_null_instance) return m_Instance;

        try { m_Instance = new Logger(); } catch(...) { }

        return m_Instance;
    }
};

const NullLogger Logger::m_null_instance;
ILogger *Logger::m_instance = &Logger::m_null_instance;

/* ... */
#define LOG Logger::Instance()->Log
LOG("Hey!");
+1

GetInstance, . ,...

if(m_Instance == NULL)
{
    try
    {
        m_Instance = new Logger();
    }
    catch (std::bad_alloc &ba)
    {
        // do something here...
    }
    catch(...){}
}

return m_Instance;
0

(1) : . (2) , . (3) HACK:

void Logger::Log( /*params*/ )
{
  if( NULL != this )
  {
    // do your logging
    ...
  }
}
0

.

singleton , . (, http://www.yolinux.com/TUTORIALS/C++Singleton.html ).

The reason I use singleton is to make sure that there is only one instance of the class (logger / settings), and yes, I know this is an abuse.

However, it seems that I need to go and try to implement something like this without using singleton.

0
source

Source: https://habr.com/ru/post/1752406/


All Articles