1

I am writing a simple garbage collector in C++. I need a singleton class GarbageCollector to deal with different types of memory. I used a Meyer's singleton pattern. But when I try to call instance, an error appears:

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

Here is the class definition.

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&);
};

I call the instance with the following line: auto gc = GarbageCollector::instance();

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
sooobus
  • 841
  • 1
  • 9
  • 22
  • In your `class` there is a comment: `Copying,[...] are not available [...]`. You are getting the error because you are copying the gc – Rakete1111 May 15 '16 at 15:37
  • Everything is said in the error message `GarbageCollector(const GarbageCollector&);` is private. You cannot call a private constructor from outside the class. – Ely May 15 '16 at 15:37
  • @Elyasin: Not everything. The surprising bit is that the `auto` variable is declared as a `GarbageCollector`, not `GarbageCollector&`. – Martin Bonner supports Monica May 15 '16 at 15:56
  • Given you are using `auto`, you might as well delete the copy constructor and assignment, rather than just declaring them private - then you can't copy even *inside* the class. – Martin Bonner supports Monica May 15 '16 at 15:57

1 Answers1

3

Change

auto gc = GarbageCollector::instance();

to

auto& gc = GarbageCollector::instance();

Otherwise gc is not a reference, then returned GarbageCollector need to be copied, but the copy ctor is private, that's why compiler complains.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405