I'm implementing a thread-safe singleton. But this aspect (singleton & thread-safe) is not part of my question.
Compare the two codes. Code 1:
#include <iostream>
using namespace std;
class DataLocation {
private:
DataLocation(std::string) {
}
public:
DataLocation& getInstance() {
std::string s = " ";
static DataLocation instance(s);
return instance;
}
};
int main() {
}
and code 2:
#include <iostream>
using namespace std;
class DataLocation {
private:
DataLocation() {
}
public:
DataLocation& getInstance() {
static DataLocation instance();
return instance;
}
};
int main() {
}
Code 1 compiles fine. Code 2 gives the following error:
15_singleton.cpp: In member function ‘DataLocation& DataLocation::getInstance()’:
15_singleton.cpp:15:34: error: cannot declare static function inside another function
static DataLocation instance();
^
15_singleton.cpp:16:12: error: invalid initialization of non-const reference of type ‘DataLocation&’ from an rvalue of type ‘DataLocation (*)()’
return instance;
^
From my point of view the only difference is that the private constructor has one, respectively zero parameters.
How can I help the compiler to understand that I'm not defining anything new, but I'm just calling the constructor? The compiler is able to understand it, when there is one parameter.
Remove the brackets
static DataLocation instance;
To create the instance with the default constructor.
Alternatively, use the braced form of initialisation.
static DataLocation instance {};
static DataLocation instance = DataLocation();
or
static DataLocation instance;
And you would probably want to declare DataLocation& getInstance(); as a static method.
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