Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++: A Simple Singleton

📅 2011-Jun-28 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, singleton ⬩ 📚 Archive

The simplest Singleton possible in C++, illustrated with a Configuration object that is used to read/write the application configuration:

class _Config
{
public:
    int _fileNum;
    int _charNum;
};

// Singleton
_Config& Config()
{
    static _Config _config;
    return _config;
}

int main()
{
    Config()._fileNum = 1024;
    Config()._charNum = 256;
    return 0;
}

Not only is this simple, it also avoids the initialization problems associated with a global static object.