创建具有构造函数的单例类,该构造函数接受被评估为运行时的参数

时间:2009-11-21 06:00:43

标签: c++ design-patterns singleton compiler-errors

我想要单例类,其对象不是静态创建的。有以下代码,当我调用 ChromosomePool :: createPool()时,我收到以下错误消息:

- > ChromosomePool.h:50:对myga :: ChromosomePool :: pool'的未定义引用< -

任何人都可以告诉我如何解决问题?

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

};  

2 个答案:

答案 0 :(得分:3)

必须定义静态成员,您只是声明pool存在于某处。

将它放在相应的源文件中:

ChromosomePool* ChromosomePool::pool = 0;

Here是该主题的 C ++ FAQ lite 中的条目。

答案 1 :(得分:1)

我通过VS2008运行你的代码并且只从链接器获得了“未解析的外部...”,这是因为静态成员池尚未实例化为gf在他的回答中说明。包括:

 ChromosomePool* ChromosomePool::pool(0);

解决这个问题,正如gf所说。

你还应该注意:

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

不会执行您想要执行的操作,因为它不会释放为池保留的内存;具体是:

delete pool;
pool=0;

确实删除了分配的内存(并隐式调用析构函数,它是析构函数的一个点)。根据我的经验,很少有情况需要明确的攻击者呼叫

相关问题