C++ Creating Global Reference of an Object

Cahit Burak Küçüksütcü picture Cahit Burak Küçüksütcü · Sep 6, 2013 · Viewed 9k times · Source

I am trying to create a global reference of an object but it seems fails or I am getting another error in Qt C++.

I have a class called 'System' which holds many objects as members. I want to access System's members from everywhere include members of System. Here is my code below:

// System.h
class System
{
public:

    Obj1* m_obj1;
    Obj2* m_obj2;

    System();
    ~System();

    static System* GetGlobalReference();
}


// System.cpp
static System* GlobalReference = 0;

System::System()
{
    if (!GlobalReference) GlobalReference = this;

    m_obj1 = new Obj1();
    m_obj2 = new Obj2();
}

System* System::GetGlobalReference()
{
    return GlobalReference;
}

// main.cpp
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    System* system = new System();

    MainWindow window;
    window.showMaximized();

    return app.exec();
}

//Obj1.h
class Obj1 : public QObject
{
    Q_OBJECT

public:
    Obj1() : QObject() {}
    ~Obj1();

public slots:
    void Import();
}

// Obj1.cpp
void Obj1::Import()
{
    QString path = QFileDialog::getOpenFileName(
            0,
            QString("Import file..."),
            QString("C:\\"),
            QString("JPEG File (*.jpg)"),
            0,
            0);
    if (System::GetGlobalReference())
        System::GetGlobalReference()->m_obj2->Import(path); // error here
    else
        // System::GlobalReference is null

}

It seems reference is not null but I get an error during runtime "Access violation reading location..." What is wrong?

Btw Obj1 is a QObject and Import method is a public slot, can the error be related with this?

Edit: Debuugger last step is here in QGenericAtomic.h

T load(const T &_q_value) Q_DECL_NOTHROW
{
    return _q_value; // -> Debugger stops here
}

Edit2: I've used Singleton pattern as the answers says but my problem still continues.

System::GetInstance()->GetObj1()->Import(path); // after this line

in "_q_value" it says ""

Answer

Extrakun picture Extrakun · Sep 6, 2013

If you wish to have global variables, I would recommend using a singleton instead.

Global variables in C++ are declared using extern, not static. See the reference for more information.