使类构造函数私有
问题描述:
我正在用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();
答
变化
auto gc = GarbageCollector::instance();
到
auto& gc = GarbageCollector::instance();
否则gc
不是一个引用,然后返回GarbageCollector
需要被复制,但是th e copy ctor是私人的,这就是编译器抱怨的原因。
在你的'class'里面有一条评论:'拷贝,[...]不可用''。你得到错误,因为你正在复制gc – Rakete1111
在错误消息“GarbageCollector(const GarbageCollector&);'是私有的。你不能从课堂外调用私人构造函数。 – Elyasin
@Elyasin:不是一切。令人惊讶的是'auto'变量被声明为'GarbageCollector',而不是'GarbageCollector&'。 –