This question already has answers here:
C++11 “auto” semantics

(3个答案)


4年前关闭。




我正在用C++写一个简单的垃圾收集器。我需要一个Singleton类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();

最佳答案

更改

auto gc = GarbageCollector::instance();


auto& gc = GarbageCollector::instance();

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

关于c++ - 将类构造函数设为私有(private),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37240192/

10-11 18:42