回调到singleton类
Callback into singleton class
我正在使用一个带有调用singleton的线程的singleton类。在一次审查中,有人问我为什么使用this指针而不是singleton实例。
我的代码和建议的更改。
class myClass : public threadWrapper
{
public:
static myClass& instance()
{
static myClass instance;
return instance;
}
// This is the callback that I have implemented
static void callback(void *me)
{
if (me != NULL)
static_cast<myClass*>(me)->doCallback();
}
// This is the suggested callback
static void callback2(void *me)
{
instance().doCallback();
}
// caller gets instance and then calls initialise()
int initialise()
{
if (initialised)
return ERROR_ALREADY_INITIALISED;
// Initialise the class
// my thread startup call
// thread wrapper class initialisation that calls pthread_create that runs the callback method with this as a parameter
// priority is a global value that difines the relative priority of the various threads.
threadWrapper::Initialise(priority, callback, this);
initialised = true;
}
private:
myClass() : initialised(false) {;}
void doCallback(void);
bool initialised;
static const int
}
那么,两者在速度上有什么显著差异吗?
threadWrapper在现有的代码库中是强制性的,我不允许使用boost。
我的理由是,如果我们需要使这不是一个单一的,那么需要更少的更改。
速度差几乎不存在。
至于代码质量,Singleton非常糟糕,我个人会放弃这两种形式,,尤其是在线程环境中。然而,假设现在已经太晚了。
问题是,如果你要传递一个指向对象的指针,为什么不首先使该对象全局化呢?如果你是,它至少应该是强类型的。然后,你只是。。。用静态方法包装成员方法?为什么要麻烦?任何有指向该类的指针的人都可以首先调用该类上的方法。这太疯狂了。
编辑:如果你坚持现有的设计,那么第二个版本肯定比第一个版本好,而且不会慢。即使您有依赖于Singleton的现有代码,那么最好尽可能重构不依赖它的代码
相关文章:
- 架构决策:返回std::future还是提供回调
- 正在为Xtensa simcall函数编写回调函数
- 如何在C++中使用非静态成员函数作为回调函数
- FLTK:按下哪个按钮 - 将数字传递给按钮的回调 (lambda)
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 用于在回调中调用解析器的设计模式
- 如何使用C++对象的成员函数作为 C 样式回调?
- Java从C++回调到C++回调
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 从不同的 cpp 调用回调函数会导致bad_function_call
- pcap_handler回调仅在使用 NPCAP v0.9991 时包含空数据包
- 不带轮询的 SDL2 事件回调
- C++存储带有可变参数的回调
- 如何使用 Node-addon-API 实现 node-nan 回调
- 处理影响跨不同线程共享对象的定时回调的最佳方法是什么?
- 访问类C++ C 样式回调
- 处理类内的回调时,必须调用对非静态成员函数的引用
- 如果 C 函数仍然可以间接执行(通过回调函数),那么将它声明为静态函数是否是一种不好的做法?
- 在C++中实现回调
- 回调到singleton类