Problem with variation on the Singleton pattern

E

Eric

I am implementing a variation on the Singleton design pattern, that
allows up to 8 objects of a class to be instantiated, and returns a
null pointer for anything more than 8.

I am running into a compile problem with GNU g++.

Here is the code:

/******************** FILE sample.h ********************/

#ifndef SAMPLE_H
#define SAMPLE_H

class Allow_8_Objects
{
public:

// Destructor is public so that it can be executed by
// "delete"ing the pointer to the object. Note that the
// Contstructor is protected so it can't be executed
// from the outside with "new" (one of the rules for
// the Singleton design pattern).
//
~Allow_8_Objects();

static Allow_8_Objects* MakeInstance( void );
// This method creates an object of this class, and
// returns its pointer. Returns NULL if no more
// objects can be made or some other error
// happened.

protected:

Allow_8_Objects();
// Protected constructor as part of the implementation
// of a modified Singleton design pattern (modified to
// allow 8 instances).

private:

static Allow_8_Objects* theInstance;
// an instance of this class. Static
// because it is used by MakeInstance(), which is
// static. This pointer is what is returned by
// MakeInstance().

static int numInstances;
// number of instances in existence. Cannot
// exceed maxObjects. Note: static.
};

#endif // SAMPLE_H

/**************** END OF FILE sample.h *****************/

/*******************************************************/

/******************* FILE sample.cpp *******************/

#include "sample.h"

static const int maxObjects = 8;
// Maximum of 8 objects allowed per node

int Allow_8_Objects::numInstances = 0;

Allow_8_Objects::Allow_8_Objects()
{
}

Allow_8_Objects::~Allow_8_Objects()
{
}

/********** HERE IS THE METHOD WITH THE PROBLEM **********/

// Make another object if not already at max.
//
Allow_8_Objects* Allow_8_Objects::MakeInstance( void )
{
theInstance = (Allow_8_Objects*)NULL;

// If we already have the max number of objects, leave
// the return pointer set to NULL, else make a new object
// and get ready to return its pointer.
//
if ( numInstances < maxObjects )
{
theInstance = new Allow_8_Objects;
}
return theInstance;
}

/*************** END OF FILE sample.cpp ****************/

Note that MakeInstance( ) is static, and theInstances and numInstances
are both static. So, MakeInstance shouldn't have any trouble
accessing theInstances and numInstances, right?

What happens when I compile this is that the cimpiler complains about
"undefined reference to Allow_8_Objects::theInstance" at lines 1, 7,
and 11 of MakeInstance(). It can find and compile numInstances just
fine (line 9 of MakeInstance()), just not theInstance.

Any ideas?
 
B

Bob Hairgrove

I am implementing a variation on the Singleton design pattern, that
allows up to 8 objects of a class to be instantiated, and returns a
null pointer for anything more than 8.

I am running into a compile problem with GNU g++.

Here is the code:

/******************** FILE sample.h ********************/

#ifndef SAMPLE_H
#define SAMPLE_H

class Allow_8_Objects
{
public:

// Destructor is public so that it can be executed by
// "delete"ing the pointer to the object. Note that the
// Contstructor is protected so it can't be executed
// from the outside with "new" (one of the rules for
// the Singleton design pattern).
//
~Allow_8_Objects();

static Allow_8_Objects* MakeInstance( void );
// This method creates an object of this class, and
// returns its pointer. Returns NULL if no more
// objects can be made or some other error
// happened.

protected:

Allow_8_Objects();
// Protected constructor as part of the implementation
// of a modified Singleton design pattern (modified to
// allow 8 instances).

private:

static Allow_8_Objects* theInstance;
// an instance of this class. Static
// because it is used by MakeInstance(), which is
// static. This pointer is what is returned by
// MakeInstance().

static int numInstances;
// number of instances in existence. Cannot
// exceed maxObjects. Note: static.
};

#endif // SAMPLE_H

/**************** END OF FILE sample.h *****************/

/*******************************************************/

/******************* FILE sample.cpp *******************/

#include "sample.h"

static const int maxObjects = 8;
// Maximum of 8 objects allowed per node

int Allow_8_Objects::numInstances = 0;

Allow_8_Objects::Allow_8_Objects()
{
}

Allow_8_Objects::~Allow_8_Objects()
{
}

/********** HERE IS THE METHOD WITH THE PROBLEM **********/

// Make another object if not already at max.
//
Allow_8_Objects* Allow_8_Objects::MakeInstance( void )
{
theInstance = (Allow_8_Objects*)NULL;

// If we already have the max number of objects, leave
// the return pointer set to NULL, else make a new object
// and get ready to return its pointer.
//
if ( numInstances < maxObjects )
{
theInstance = new Allow_8_Objects;
}
return theInstance;
}

/*************** END OF FILE sample.cpp ****************/

Note that MakeInstance( ) is static, and theInstances and numInstances
are both static. So, MakeInstance shouldn't have any trouble
accessing theInstances and numInstances, right?

What happens when I compile this is that the cimpiler complains about
"undefined reference to Allow_8_Objects::theInstance" at lines 1, 7,
and 11 of MakeInstance(). It can find and compile numInstances just
fine (line 9 of MakeInstance()), just not theInstance.

Any ideas?

You are getting a linker error because you didn't initialize
theInstance. It compiles just fine, at least on my compiler, but it
won't link. Put this in your .cpp file:

Allow_8_Objects *Allow_8_Objects::theInstance = 0;

Also, you don't #include whatever header defines NULL (probably
stddef.h??). But using 0 works just as well.

Some other things to think about:

(1) You have declared the default constructor protected, implying that
other classes will eventually derive from this one. If you ever delete
such a class through the base class pointer, you need to provide a
virtual destructor. Otherwise, you get undefined behavior.

(2) When someone deletes an instance of the class, what happens
(should happen) to numInstances?

(3) What about copying and assignment? Generally you wouldn't want to
allow copying a singleton, but since you have more than one, perhaps
it would make sense. If not, you should declare these private but
don't implement them.

(4) You'll need to think about synchronization issues in case these
objects will be created in different threads.

(5) Since you have a fixed ceiling of eight objects, I wonder if it
wouldn't make more sense to create eight static objects up front and
that way avoid the ensuing memory management problems? But we don't
have enough information yet about what you are trying to do.
 
E

Eric

You are getting a linker error because you didn't initialize
theInstance. It compiles just fine, at least on my compiler, but it
won't link. Put this in your .cpp file:

Allow_8_Objects *Allow_8_Objects::theInstance = 0;

Good afternoon, Bob.

Thanks, that did it. :)

And thanks for your other items of advice. I will consider each and
will probably implement most. I'm relatively new at C++, about 2
years' experience over the last 4 years (though I have about 21 years'
experience with C) and some of the more exotic features of the
language like virtual destructors still leave me scratching my head a
bit. But, I'm learning. :)
(2) When someone deletes an instance of the class, what happens
(should happen) to numInstances?

It should (will) get set to zero, as will the pointer to the instance
of the class.
(3) What about copying and assignment? Generally you wouldn't want to
allow copying a singleton, but since you have more than one, perhaps
it would make sense. If not, you should declare these private but
don't implement them.

I don't think that I plan to copy them (if I understand correctly what
you mean), but what do you mean by declaring these private (what are
"these") but not implementing them?
(4) You'll need to think about synchronization issues in case these
objects will be created in different threads.

Fortunately this is a single-threaded application so I'm pretty safe
there.
(5) Since you have a fixed ceiling of eight objects, I wonder if it
wouldn't make more sense to create eight static objects up front and
that way avoid the ensuing memory management problems? But we don't
have enough information yet about what you are trying to do.

The reason I don't do that is that not all 8 of them will necessarily
get used, in fact most often only one will be used, occasionally two,
rarely more than that, and if they don't get used I don't want them
occupyingr memory unnecessarily.

Thanks...

Eric
 
B

Bob Hairgrove

Good afternoon, Bob.

Thanks, that did it. :)

:)
And thanks for your other items of advice. I will consider each and
will probably implement most. I'm relatively new at C++, about 2
years' experience over the last 4 years (though I have about 21 years'
experience with C) and some of the more exotic features of the
language like virtual destructors still leave me scratching my head a
bit. But, I'm learning. :)


It should (will) get set to zero, as will the pointer to the instance
of the class.


I don't think that I plan to copy them (if I understand correctly what
you mean), but what do you mean by declaring these private (what are
"these") but not implementing them?

If you don't declare them, the compiler will generate default versions
of the copy constructor and the assignment operator for you.
Unfortunately, there might not do what you want. E.g., if you allocate
memory dynamically anywhere and have a pointer as member variable, you
will want to make sure that the memory is actually copied and not just
the pointer. Therefore, to ensure that objects are properly copied,
you need to implement a copy constructor and assignment operator that
do the right thing.

However, if you wish to disallow copying and assignment, you can
declare the copy constructor and the assignment operator as "private"
and simply leave out any implementation or function body for these.
That way, the compiler will generate an error when a client tries to
copy or assign to one of the objects.
Fortunately this is a single-threaded application so I'm pretty safe
there.


The reason I don't do that is that not all 8 of them will necessarily
get used, in fact most often only one will be used, occasionally two,
rarely more than that, and if they don't get used I don't want them
occupyingr memory unnecessarily.

How did you come up with the magic number 8 in that case? Seems to me
to be a bit arbitrary...
 
E

Eric

How did you come up with the magic number 8 in that case? Seems to me
to be a bit arbitrary...

Mostly because the project engineer said "Allow for a maximum of 8"
and I snapped to attention, rendered a brisk salute, and said "Yes,
sir". :)
 
L

Luke Meyers

Eric said:
Mostly because the project engineer said "Allow for a maximum of 8"
and I snapped to attention, rendered a brisk salute, and said "Yes,
sir". :)

Sure, but it's more fun like:

template <size_t n>
class allow_n_instances;

:)

Luke
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,149
Members
46,695
Latest member
StanleyDri

Latest Threads

Top