X39
X39

Reputation: 827

C++ Singleton - Prevent ::instance() to variable

Given the singleton class

class MySingleton
{
    // ...
    public:
        MySingleTon& instance() { /* ... */ }
};

is it possible to prevent:

int main()
{
    // the following should cause some error
    MySingleton& singleton = MySingleton::instance();
}

while still allowing:

int main()
{
    // Only directly accessing MySingleton::instance().SomeMethod should be possible
    MySingleton::instance().some_method();
}

Extra example

int main()
{
    // Following two lines should error
    MySingleton& singleton = MySingleton::instance();
    singleton.some_method();
    
    // Following line should NOT error
    // Additionally it should be the only way to access any MySingleton method besides MySingleton::instance
    MySingleton::instance().some_method();
}

Upvotes: 0

Views: 133

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597610

The only way I know to do what you are looking for is to make instance() itself be private so code that is outside of MySingleton can't call it directly, then add a static method to MySingleton that is public and uses instance() internally as needed, eg:

class MySingleton
{
    // ...
    private:
        MySingleton() { /* ... */ }
        static MySingleton& instance() {  static MySingleton inst; return inst; }
    public:
        static void do_method() { instance().some_method(); }
};

int main()
{
    MySingleton& singleton = MySingleton::instance(); // <-- ERROR
    singleton.some_method();
    
    MySingleton::do_method(); // <-- OK
}

Upvotes: 2

Related Questions