使类构造函数私有

时间:2016-05-15 15:34:43

标签: c++ oop c++11 constructor auto

我正在用C ++编写一个简单的垃圾收集器。我需要一个单独的类GarbageCollector来处理不同类型的内存。 我使用了迈耶的单身模式。但是当我尝试调用实例时,会出现错误:

 error: ‘GarbageCollector::GarbageCollector(const GarbageCollector&)’ is private
    GarbageCollector(const GarbageCollector&);
    ^

这是课程定义。

class GarbageCollector //Meyers singleton (http://cpp-reference.ru/patterns/creational-patterns/singleton/)
{
 public:
    static GarbageCollector& instance(){
        static GarbageCollector gc; 
        return gc; 
    }   
    size_t allocated_heap_memory;
    size_t max_heap_memory;
private:
    //Copying, = and new are not available to be used by user.
    GarbageCollector(){};
    GarbageCollector(const GarbageCollector&);
    GarbageCollector& operator=(GarbageCollector&);
};

我用以下行调用实例: auto gc = GarbageCollector::instance();

1 个答案:

答案 0 :(得分:3)

更改

auto gc = GarbageCollector::instance();

auto& gc = GarbageCollector::instance();

否则gc不是引用,则返回GarbageCollector需要复制,但复制ctor是私有的,这就是编译器抱怨的原因。