如何在C中创建Singleton? [英] How to create a Singleton in C?

查看:96
本文介绍了如何在C中创建Singleton?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C中创建单身人士的最佳方法是什么?一个并发解决方案将是很好的。



我知道C不是单身人士使用的第一种语言。

解决方案

首先,C不适合OO编程。如果你这样做,你一直在战斗。其次,单例只是一些封装的静态变量。所以你可以使用一个静态的全局变量。然而,全球变量通常与他们相关的病毒太多。您可以使用本地静态变量函数,如下所示:

  int * SingletonInt(){
static int instance = 42;
return& instance;
}

或更聪明的宏:

  #define SINGLETON(t,inst,init)t * Singleton _ ## t(){\ 
static t inst = init; \
return& inst; \
}

#include< stdio.h>

/ *实际定义* /
SINGLETON(float,finst,4.2);

int main(){
printf(%f\\\
,*(Singleton_float()));
return 0;
}

最后,请记住,单身人士大多被滥用。很难让他们正确,特别是在多线程环境下...


What's the best way to create a singleton in C? A concurrent solution would be nice.

I am aware that C isn't the first language you would use for a singleton.

解决方案

First, C is not suitable for OO programming. You'd be fighting all the way if you do. Secondly, singletons are just static variables with some encapsulation. So you can use a static global variable. However, global variables typically have far too many ills associated with them. You could otherwise use a function local static variable, like this:

 int *SingletonInt() {
     static int instance = 42;
     return &instance;
 }

or a smarter macro:

#define SINGLETON(t, inst, init) t* Singleton_##t() { \
                 static t inst = init;               \
                 return &inst;                       \
                }

#include <stdio.h>  

/* actual definition */
SINGLETON(float, finst, 4.2);

int main() {
    printf("%f\n", *(Singleton_float()));
    return 0;
}

And finally, remember, that singletons are mostly abused. It is difficult to get them right, especially under multi-threaded environments...

这篇关于如何在C中创建Singleton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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