C ++检查单例指针 [英] C++ checking singleton pointers

查看:101
本文介绍了C ++检查单例指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,它有一个(Qt C ++)单例记录器类。 GetInstance()实现是:

I have an application, which has a (Qt C++) singleton logger class. The GetInstance() implementation is:

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



现在我在.h文件中有以下宏:
#define LOG Logger: :Instance() - > Log

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

只要new()操作正常,一切正常。什么是最好的方法,以确保指针已设置(我在想一些try-catch块捕捉std :: bad_alloc,但我不知道如何实现在宏)?我创建了一个解决方法,似乎工作,但不漂亮:

Everything is fine as long as new() operation works. What is the best way to ensure that pointer has set (I was thinking some try-catch blocks to catch the std::bad_alloc, but I don't know how to implement that in a macro)? I have created a workaround, which seems to work but is not pretty:

#定义LOG if(Logger :: Instance())Logger :: Instance > Log

"#define LOG if(Logger::Instance()) Logger::Instance()->Log"

另外,我想知道如果我的对象有很多getters / setters(例如setPath(),getSize()...)目前,我有一个宏:

In addition, I would like to know what if my object has a lot getters/setters (e.g. setPath(), getSize()...)? Currently, I have a macro:

#define SET Settings :: Instance()

"#define SET Settings::Instance()"

代码我可以使用SET-> setPath(abc);或SET-> getSize();

and in code I'm able to use SET->setPath("abc"); or SET->getSize();

在这种情况下,我的丑陋的解决方法不工作,因为它需要为每个方法单独的宏。

In this case my ugly workaround does not work, because it requires separate macro for every method. Any tips how I can improve that?

推荐答案

任何提示如何改善?

不要使用可怕的设计模式 - >不要遇到问题。通常,人们使用更类似于

Don't use a terrible design pattern -> don't get problems. Normally, people use something more akin to

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

但是单例模式通常是绝对可怕的。请改用应用程序实例模式。

But the singleton pattern is in general absolutely terrible. Use the application instance pattern instead.

这篇关于C ++检查单例指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆