2016-05-15 121 views
1

我正在用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();

+0

在你的'class'裏面有一條評論:'拷貝,[...]不可用''。你得到錯誤,因爲你正在複製gc – Rakete1111

+0

在錯誤消息「GarbageCollector(const GarbageCollector&);'是私有的。你不能從課堂外調用私人構造函數。 – Elyasin

+0

@Elyasin:不是一切。令人驚訝的是'auto'變量被聲明爲'GarbageCollector',而不是'GarbageCollector&'。 –

回答

3

變化

auto gc = GarbageCollector::instance(); 

auto& gc = GarbageCollector::instance(); 

否則gc不是一個引用,然後返回GarbageCollector需要被複制,但是th e copy ctor是私人的,這就是編譯器抱怨的原因。