Singleton implementation static member error

Asked

Viewed 59 times

2

When implementing the Singleton standard the compiler gives the following error:

include graphdata. h|21|error: 'constexpr' needed for in-class initialization of Static data Member 'graphdata* graphdata::instance' of non-integral type [-fpermissive]|

The code I made is this::

class graphdata
{
    public:
        static graphdata& getinstance(){
            if(!instance)
                instance = new graphdata();
            return *instance;
        }
        void dfsR();
        graphdata(graphdata const&) = delete;
        void operator = (graphdata const&) = delete;
    protected:

    private:
        graphdata();
        static graphdata* instance = 0;
};

1 answer

1

This is exactly what is written, if you want to initialize a value in the class declaration you need to be a constant expression (constexpr). If it cannot be constant it must initialize in the static constructor or its normal code before using the variable.

  • I even tried, but got the error saying *instance is private.

  • 1

    That’s another mistake, I showed you how to fix this mistake. But I suggest you start doing simpler things first. You are skating on basic points that you must learn before trying to do something more complex.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.