【问题标题】:create singleton class that has constructor which accepts arguments that are evaluated runtime创建具有构造函数的单例类,该构造函数接受在运行时评估的参数
【发布时间】:2009-11-21 06:00:43
【问题描述】:

我想要一个单例类,它的对象不是静态创建的。具有以下代码,当我调用 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;
    }

};  

【问题讨论】:

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


    【解决方案1】:

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

    把这个放到对应的源文件中:

    ChromosomePool* ChromosomePool::pool = 0;
    

    HereC++ FAQ lite 中主题的条目。

    【讨论】:

    • 那么他会得到一个链接器错误,但这似乎是一个编译问题
    【解决方案2】:

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

     ChromosomePool* ChromosomePool::pool(0);
    

    按照 gf 的说法解决这个问题。

    您还应该注意:

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

    不会做你想做的事,因为它不会释放为池保留的内存;具体来说:

    delete pool;
    pool=0;
    

    确实删除了分配的内存(并隐式调用析构函数,这是析构函数的点)。根据我的经验,很少有需要显式 destrutor 调用的情况

    【讨论】:

    • unresolved external 在 VC 和 undefined reference 在 gcc 中是一样的。
    猜你喜欢
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 2022-01-18
    • 2023-01-01
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    • 2013-10-30
    相关资源
    最近更新 更多