C++ Creating Global Reference of an Object

10.9k views Asked by At

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 ""

3

There are 3 answers

0
Cahit Burak Küçüksütcü On BEST ANSWER

I've solved my problem. The problem was caused by Obj1->Import method but during debug in qt, debugger is not accessing inside the method when I press F11(Step Into). I cannot figure it out why?

2
Extrakun On

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.

0
Pierre Fourgeaud On

If you want only one instance of your System class, you should use the Singleton pattern.

But, the Singleton pattern should be used when you want an unique instance of a class, the reason should not be when you want to have an object global. Even if using this pattern, your instance is accessible from everywhere.

Look at this article about Singleton design pattern, it may be useful in your case.

Also, in C++ the declaration of global variable is done with extern, not static.