Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ singleton, strange error [duplicate]

Tags:

c++

c++11

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.

like image 645
PeptideChain Avatar asked Aug 28 '26 03:08

PeptideChain


2 Answers

Remove the brackets

static DataLocation instance; 

To create the instance with the default constructor.

Alternatively, use the braced form of initialisation.

static DataLocation instance {};
like image 77
Sebastian Hoffmann Avatar answered Aug 29 '26 18:08

Sebastian Hoffmann


static DataLocation instance = DataLocation(); 

or

static DataLocation instance;

And you would probably want to declare DataLocation& getInstance(); as a static method.

like image 21
Teivaz Avatar answered Aug 29 '26 19:08

Teivaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!