I have the following problem. I have a singleton with a getInstance member function that returns an instance. I call this somewhere in code and for some reason VC tries to call the copy constructor. Why is this? How do I fix this?
The header:
class FileSystemEntryCollection {
public:
static FileSystemEntryCollection &getInstance();
private:
FileSystemEntryCollection();
FileSystemEntryCollection(FileSystemEntryCollection const&);
void operator=(FileSystemEntryCollection const&);
}
Source file:
FileSystemEntryCollection &FileSystemEntryCollection::getInstance() {
static FileSystemEntryCollection instance = FileSystemEntryCollection();
return instance;
}
The following line calls the copy constructor:
auto collection = FileSystemEntryCollection::getInstance();
I've tried to leave in the relevant code, let me know if something else is needed.
The constructor, copy constructor and assignment operator are all private to ensure that the programmer using the singleton class can only create a single instance of the class using only the Instance() function.
It is possible to have a protected constructor in a singleton class. If you want to have polymorphic behavior on your Singleton you can make it an abstract class, set the constructor to protected and delegate creation of the instance to one of the concrete sub classes.
EDIT: IF you have a singleton-class you won´t need both constructor. All your initializations can be done by the default one, where you set all important members of that instance whereas the static one can be omitted.
Singleton Class allow for single allocations and instances of data. It has normal methods and you can call it using an instance. To prevent multiple instances of the class, the private constructor is used.
auto collection = FileSystemEntryCollection::getInstance();
needs to be:
auto& collection = FileSystemEntryCollection::getInstance();
^
auto
on its own is never a reference type.
With a different compiler you'll get the same error for the initialization of instance
.
static FileSystemEntryCollection instance = FileSystemEntryCollection();
The =
here calls for copy construction: formally, the compiler creates a temporary (FileSystemEntryCollection()
), and copies that into instance
. However, in this situation, compilers are allowed to skip the copy construction and construct the object directly in place. That's what your compiler is doing. But compilers aren't required to do this.
Better:
static FileSystemEntryCollection instance;
which uses the default constructor to create instance
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With