开发者

create singleton class that has constructor which accepts arguments that are evaluated runtime

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 chromosomeL开发者_JAVA百科ength;

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

};  


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜