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

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

问题描述

在 C 中创建单例的最佳方法是什么?并发解决方案会很好.

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

我知道 C 不是您用于单身人士的第一种语言.

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

推荐答案

首先,C 不适合 OO 编程.如果你这样做,你会一直战斗.其次,单例只是带有一些封装的静态变量.所以你可以使用静态全局变量.然而,全局变量通常有太多与之相关的弊端.否则,您可以使用函数局部静态变量,如下所示:

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;
 }

或更智能的宏:

#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
", *(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 中创建单例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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