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

问题描述

我要创建C中的单
什么是最好的方法是什么?

I want to create a singleton in C.What's the best way?

并行解决方案将是很好的。

A concurrent solution would be nice..

编辑 - 我知道C是不是你会使用一个单例的第一langague,如果是这个问题就简单多了。

Edit - I am aware that C isn't the first langague you would use for a Singleton, If it was the question was much simpler.

推荐答案

首先,C是不适合面向对象编程。如果你这样做你会战斗到底。其次,单身人士与一些封装的只是静态变量。所以,你可以使用一个静态全局变量。然而,全局变量通常具有关联太多的弊病。否则,你可以使用函数局部静态变量,就像这样:

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\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单身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 00:55