1

Possible Duplicate:
How to create a Singleton in C ?

Hello, if I have a structure definition as follows:

struct singleton
{
    char sharedData[256];
};

Can I impose the singleton pattern on instance variables of the above structure in C [not in C++]?

Community
  • 1
  • 1
Swaranga Sarma
  • 13,055
  • 19
  • 60
  • 93
  • 1
    Singleton? Instance variables? What's that OO terminology doing in a C context? :) But you can do whatever YOU want with your struct, can't you? I don't see a way to impose any restrictions on others including your .h with the definition. It's C, as you said. – Mörre Mar 02 '11 at 18:21

2 Answers2

9

If you just forward declare your struct in the header file, it will be impossible for clients to create an instance of it. Then you can provide a getter function for your single instance.

Something like this:

.h:

#ifndef FOO_H
#define FOO_H

struct singleton;

struct singleton* get_instance();

#endif

.c:

struct singleton
{
    char sharedData[256];
};

struct singleton* get_instance()
{
    static struct singleton* instance = NULL;

    if (instance == NULL)
    {
        //do initialization here
    }

    return instance;
}
mtvec
  • 17,846
  • 5
  • 52
  • 83
  • don't you need getters for the `sharedData` as well since the header doesn't expose it? – NG. Mar 02 '11 at 18:41
  • @SB: Sure, but I wanted to keep the example simple. – mtvec Mar 02 '11 at 20:28
  • @Mörre: The variable needs to be initialized in the `//do initialization here` part, obviously. That's only done the first time the function is called since the variable is declared `static` so it will keep the initialized value after the first call. – mtvec Mar 02 '11 at 20:29
3

You can just declare:

char sharedData[256];

That's a global variable, no struct and singleton-antipattern needed.

Bernd Elkemann
  • 23,242
  • 4
  • 37
  • 66
  • @enznme because classes in c++/c are very much similar to struct thus don't you think we must use structure for keeping single copy of object (in this case single struct object) for ensuring single instance concept in singleton pattern. – Algorithmist Mar 02 '11 at 18:53
  • @Algorithmist: There is no way to prevent a skilled programmer from creating multiple instances. Aside from that: Singleton is a so-called antipattern. The most serious (of many) problems it creates are: 1) Prevents usability of your code as a library 2) Prevents testing because class cannot be instantiated multiple times. – Bernd Elkemann Mar 02 '11 at 19:07