It could be null!



  • Discovered one coworker repeatedly checks his singletons for null.

    // definition
    class Singleton
    {
    public:
         static Singleton* Instance() {
             if (!Instance_)
                 Instance_ = new Singleton;
             return Instance_;
         }
    private:
         Singleton* Instance_;
    };
    

    Then throughout the code base:

    Singleton* instance = Singleton::Instance();
    if (!instance) {
        cerr << "No Singleton Available!" << endl;
        abort();
    }
    

    I cannot figure out what he could have been thinking. If it's anything like some other guys I work with, it could be "It's a pointer, so you have to check it, it could change any time!"


  • Discourse touched me in a no-no place

    @Snuffles said:

    I cannot figure out what he could have been thinking.

    "What if nobody's created it yet ⁉"



  • That could be it. There are some wonderful 'singleton' patterns in play:

    class Singleton {
    public:
        static void Init(int arg1, ..., double arg5000) {
            if (!Instance_) Instance_ = new Singleton();
            return Instance_;
        }
        static Singleton* Instance() { return Instance_; }
    private:
        static Singleton* Instance_;
    };
    

    I've seen the following half a dozen times or so deep in the codebase guts:

    class Singleton {
    public:
        Singleton(int arg1, ..., double arg5000) {
            if (Instance_) {
                cerr << "Only one singleton allowed per program!\n";
                abort();
            }
    
            Instance_ = this;
        }
    private:
        static Singleton* Instance_;
    };

  • Discourse touched me in a no-no place

    @Snuffles said:

    Singleton(int arg1, ..., double arg5000) {
    if (Instance_) {
    cerr << "Only one singleton allowed per program!\n";

    So much wrongness packed into so few lines!

    Have these people never heard of non-public constructors? Isn't that part of the pattern?


  • Banned

    TRWTF is having singleton at all.



  • @FrostCat said:

    So much wrongness packed into so few lines!

    Have these people never heard of non-public constructors? Isn't that part of the pattern?

    In their defense, these tended to be written circa 1991-93. Still a poor implementation though.


Log in to reply