views:

111

answers:

2

I want to have singleton class that its object is not statically created. having the following code, when I call ChromosomePool::createPool() I get the following error message :

--> ChromosomePool.h:50: undefined reference to `myga::ChromosomePool::pool' <--

Can anyone please tell me how can I solve the problem ?

class ChromosomePool {

private:
    double * array;
    const int len;
    const int poolSize;
    const int chromosomeLength;

    static ChromosomePool* pool;

    ChromosomePool(int size_of_pool, int length_of_chromosom):
    poolSize(size_of_pool) , chromosomeLength(length_of_chromosom),
    len(size_of_pool*length_of_chromosom){
        array = new double[len];
    }

public:

    static void createPool(int size_of_pool, int length_of_chromosom) {
        if(pool) {
            DUMP("pool has already been initialized.");
            exit(5);
        }

        pool = new ChromosomePool(size_of_pool,length_of_chromosom);
    }

    static void disposePool() {
        if( !pool ) {
            DUMP("Nothing to dispose");
            exit(5);
        }

        pool ->~ChromosomePool();
        pool = NULL;
    }

    static ChromosomePool* instace() {
        if( !pool ) {
            DUMP("Using pool before it is initialized");
            exit(5);
        }
        return pool;
    }


    ~ChromosomePool() {
        delete[] array;
    }

};
+3  A: 

Static members have to be defined, you are only declaring pool as existing somewhere.

Put this in the corresponding source file:

ChromosomePool* ChromosomePool::pool = 0;

Here is the entry in C++ FAQ lite for the subject.

Georg Fritzsche
Then he would have been getting a linker error but this seems to be a compilation issue
Elemental
`undefined reference` is a linker error.
Georg Fritzsche
+1  A: 

I ran your code through VS2008 and only got 'unresolved external ...' from the linker which is because the static member pool has not been instantiated as gf says in his answer. Including:

 ChromosomePool* ChromosomePool::pool(0);

solves this as gf says.

You should also note that:

pool ->~ChromosomePool();
pool = NULL;

doesn't do what you want to do as it doesn't deallocate the memory reserved for pool; specifically:

delete pool;
pool=0;

does remove the allocated memory (and implicitly calls the destructor which is the point of the destructor). In my experience there are very few situation where an explicit destrutor call is required

Elemental
`unresolved external` in VC is the same as `undefined reference` in gcc.
Georg Fritzsche