dimanche 8 novembre 2020

Why doesn't my singleton implementation compile? (C++)

I am new to C/C++

I tried to implement singleton-pattern.

why doesn't following code not compile. In javascript there is no problem implementing the singleton pattern in a similar fashion. (https://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript)

I thought that when I declare the pointer *singleton_instance static it could be accessed by the static method. But G++ gives the error

singleton_pattern_nullptr.cpp:12:20: warning: ‘constexpr’ needed for in-class initialization of static data member ‘Grammar* Grammar::singleton_instance’ of non-integral type [-fpermissive]
   12 |    static Grammar *singleton_instance = NULL;

But even with

#include <iostream>
#include <stdio.h>    
#define NULL nullptr
    
class Grammar {         
protected:
    Grammar() {};
    static Grammar *singleton_instance = NULL;          
public:         
    Grammar& getInstance();     
}; 

static Grammar& Grammar::getInstance() {
    if(singleton_instance == NULL) {
        // no star with new
        singleton_instance = new Grammar();
    }           
    return *singleton_instance;
}
    
int main(int argc, char* argv[]) {          
    Grammar *grammar;       
    grammar = Grammar::getInstance();
            
    return 0;
}

Now when I define

static constexpr Grammar *singleton_instance = NULL;

g++ spawns the error message...

singleton_pattern_nullptr.cpp:23:23: error: assignment of read-only variable ‘Grammar::singleton_instance’
   23 |    singleton_instance = new Grammar();

and still ...

singleton_pattern_nullptr.cpp:33:34: error: cannot call member function ‘Grammar& Grammar::getInstance()’ without object
   33 |   grammar = Grammar::getInstance();

I thought I could make it mutable but in this thread (static mutable member variables in C++?) I read that it shouldn't be necessary for a static member variable to be specified mutable in order to be that (mutable) because this should already be the case anyway.

So please tell me where my error is and if an implementation of a singleton like I thought of above (see javascript example) is possible in C++ or not.

Thanks

Aucun commentaire:

Enregistrer un commentaire