【发布时间】:2016-09-11 10:23:07
【问题描述】:
我正在用 C++ 编写一个简单的垃圾收集器。我需要一个单例类 GarbageCollector 来处理不同类型的内存。 我使用了 Meyer 的单例模式。但是当我尝试调用实例时,出现错误:
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();
【问题讨论】:
-
在您的
class中有一条评论:Copying,[...] are not available [...]。您收到错误是因为您正在复制 gc -
错误消息
GarbageCollector(const GarbageCollector&);中所说的一切都是私人的。您不能从类外部调用私有构造函数。 -
@Elyasin:不是所有的。令人惊讶的是
auto变量被声明为GarbageCollector,而不是GarbageCollector&。 -
鉴于您使用的是
auto,您不妨删除复制构造函数和赋值,而不仅仅是将它们声明为私有 - 然后您甚至无法复制 inside类。
标签: c++ oop c++11 constructor auto