C++ Creating Global Reference of an Object - c++

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

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.

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.

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?

Related

Singleton pattern with gtk3 and gtkmm

I'm working on a gui app with cpp and gtkmm3.
In this app, some widgets require the singleton pattern to implement such as window (because i want just one window in all over the app)
this is my header file:
class MyWindow : public Gtk::ApplicationWindow {
public:
MyWindow(BaseObjectType *pWindow, Glib::RefPtr<Gtk::Builder> builder);
~MyWindow();
MyWindow(MyWindow const&) = delete;
void operator=(MyWindow const&) = delete;
static MyWindow* getInstance();
private:
MyWindow();
};
and source file is :
MyWindow::MyWindow(){}
MyWindow::MyWindow(BaseObjectType *pWindow, Glib::RefPtr<Gtk::Builder> refBuilder)
: Gtk::ApplicationWindow(pWindow),
builder(refBuilder) {
}
MyWindow::~MyWindow() {}
MyWindow *MyWindow::getInstance() {
static MyWindow *window;
return window;
}
my question is:
Is there a more appropriate and reasonable pattern instead singleton pattern ?
Is using this pattern suitable for the interface widgets and gui app ?
The major problem with the Singleton design pattern is that it gives you:
a single instance AND
global access.
The single instance aspect of the singleton is what people usually are looking for (like in your case), but not global access.
The usual "alternative" to this is to declare a MyWindow instance and then inject it to anyone who needs it. This is known as dependency injection. So you have something like:
void DoSomeThingOnWindow(MyWindow& p_window)
{
p_window.DoSomething();
}
// At the beginning:
MyWindow window;
// Everywhere else:
DoSomeThingWithTheWindow(window);
instead of:
void DoSomeThingOnWindow()
{
// Global access:
MyWindow* window = MyWindow::getInstance();
window->DoSomething();
}
// Everywhere:
DoSomeThingWithTheWindow();
The "bad" side of dependency injection over a singleton is that it will not enforce the single instance. However, if you use it everywhere and carefully, you can pass a single instance all around and not have global access, which will have so much more benefits.

Do I need to delete point in plugin class in Qt?

Now, I perfect my question.The pointer m_Core will be initialized and GetCore() will be called first for sure.The most I concerned is the document said root component will be deleted automatically when QPluginLoader is fully unloaded,and I don't know how Qt process the memory when Qt destruct QPluginloader and instances. If Qt will delete the Object before the destruction of QPluginLoader, I don't need to free it manually. In fact, when I invalid the delete m_Core, Qt reports no err, if I valid it, Qt will report segment fault, so Qt must destruct Mplugin class before call ~Mplugin() function.
The m_Core is derived class of QWidget:
SF_Core.h
#include <QWidget>
class SF_Core:public QWidget
{
SF_Core(QWidget* parent):QWidget(parent){}
~SF_Core(){}
};
and I use it through QPluginLoader in my project like this:
mainWindow.h
#include "MInterface.h"
#include "SF_Core.h"
#include <QWidget>
class MainWindow:public QWidget
{
Q_Object
MainWindow();
~MainWindow();
private:
MInterface* interface;
QObject* plugin;
MCore* core;
}
mainWindow.cpp
void mainWindow::mainWindow()
{
QPluginLoader loader("SF_Core.dll");
plugin = loader.instance();
interface = qobject_cast<MInterface* >(plugin);
core = interface->GetCore();
}
I have a plugin class derived from MIngerface class in Qt program, and override the function GetCore() in MIngerface.
#include "SF_Core.h"
class Mplugin:public QObject,MInterface
{
Q_OBJECT
Q_PLUGIN_METADATA(IID INTERFACE_ID)
Q_INTERFACES(MInterface)
public:
Mplugin();
~Mplugin(){
delete m_Core;
}
SF_Core* GetCore(){
m_Core = new SF_Core;
return m_Core;
}
private:
SF_Core* m_Core;
};
In main program, I load the plugin by QPluginLoader,and use instance() to get the root component. When I terminated the program, it crashed.I found the err came from the sentence delete m_Core; If I don't delete m_Core, will it cause memory leak?
Initial short answer
Keeping in mind the principle of ownership, most probably yes: it will cause memory leak.
Also, consider that each call to GetCore will allocate a new instance and create memory leak.
However, without having a full example, it is difficult to understand how SF_Core is used, especially if it ownership is transferred or not.
Stack variable fix
What if you use an internal stack value? (Not the best practice, however to publish internal properties)
SF_Core* GetCore()
{
return &m_Core;
}
private:
SF_Core m_Core;
Alternative using shared_ptr
An alternative is to use smart pointer (which I highly recommend over raw pointers whenever possible):
using SfCorePtr = std::shared_ptr<SF_Core>;
SfCorePtr GetCore()
{
if (!m_CorePtr)
{
m_CorePtr = std::make_shared<SF_Core>(); // Lazy creation
}
return m_CorePtr;
}
private:
SfCorePtr m_Core;
Hint: to be even more pedantic, the use of std::weak_ptr allows to give access to a smart pointer without providing it ownership: If GetCore return a weak_ptr, the ownership of m_Core is keep inside this object and the ownership stay in a tree-shape instead of graph-shape.
Minimal fix
Otherwise, just fixing your code:
#include "Mcore.h"
class Mplugin:public QObject,MInterface
{
Q_OBJECT
Q_PLUGIN_METADATA(IID INTERFACE_ID)
Q_INTERFACES(MInterface)
public:
Mplugin();
virtual ~Mplugin(){
delete m_Core;
}
SF_Core* GetCore(){
if (nullptr == m_Core){
m_Core = new SF_Core;
}
return m_Core;
}
private:
SF_Core* m_Core=nullptr;
};

QJSEngine - exposing classes and throwing errors

I am trying to create a standard JS library that is mostly shaped like Qbs (which uses deprecated QScriptEngine) with QJSEngine, so people who make Qt software can add things like file-operations to their plugin JS environment.
You can see the repo here
I've got basic classes exposed to the JS engine, like this:
QJSEngine jsEngine;
jsEngine.installExtensions(QJSEngine::AllExtensions);
jsEngine.globalObject().setProperty("BinaryFile", jsEngine.newQMetaObject(&Qbs4QJS::BinaryFile::staticMetaObject));
but I can's seem to figure out how to get a reference to the QJSEngine, inside a function, so I can throw an error:
Q_INVOKABLE BinaryFile(const QString &filePath, QIODevice::OpenModeFlag mode = QIODevice::ReadOnly) {
m_file = new QFile(filePath);
if (!m_file->open(mode)) {
// how do I get jsEngine, here
jsEngine->throwError(m_file->errorString());
}
}
I'd like it if I could somehow derive the calling engine from inside the function, so the class could be exposed to several separate engine instances, for example.
I saw QScriptable and it's engine() method, but couldn't figure out how to use it.
I added
Depends { name: "Qt.script" }
in my qbs file, and
#include <QtScript>
but it still isn't throwing the error with this (just fails silently):
#include <QObject>
#include <QString>
#include <QFile>
#include <QIODevice>
#include <QFileInfo>
#include <QtScript>
namespace Qbs4QJS {
class BinaryFile : public QObject, protected QScriptable
{
Q_OBJECT
public:
Q_ENUM(QIODevice::OpenModeFlag)
Q_INVOKABLE BinaryFile(const QString &filePath, QIODevice::OpenModeFlag mode = QIODevice::ReadOnly) {
m_file = new QFile(filePath);
// should check for false and throw error with jsEngine->throwError(m_file->errorString());
if (!m_file->open(mode)){
context()->throwError(m_file->errorString());
}
}
private:
QFile *m_file = nullptr;
};
} // end namespace Qbs4QJS
I may be confused about it, too, but it seems like it's using QScriptEngine, which I'm trying to get away from.
What is the best way to accomplish the task of adding a class that QJSEngine can use, which has cpp-defined methods that can throw errors in the calling engine?
The object under construction does not have any association with QJSEngine yet. So you can only do one of the following alternatives:
Store the engine instance in a static variable if you can ensure that there is only ever one instance of QJSEngine in your whole application.
Store the engine instance in a thread-local variable (QThreadStorage) if you can ensure that there is only one engine per thread.
Set the current active engine in the current thread right before evaluating your JS code since. This might be the easiest and yet robust solution.
Retrieve the engine from a QJSValue parameter.
Implement a JS wrapper for the constructor
Solution 4.: Passing the engine implicitly via a QJSValue parameter.
I assume that your throwing constructor always has a parameter. QJSValue has a (deprecated) method engine() which you then could use. You can replace any parameter in a Q_INVOKABLE method with QJSValue instead of using QString and friends.
class TextFileJsExtension : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE TextFileJsExtension(const QJSValue &filename);
};
TextFileJsExtension::TextFileJsExtension(const QJSValue &filename)
{
QJSEngine *engine = filename.engine();
if (engine)
engine->throwError(QLatin1String("blabla"));
}
I guess there is a reason why it is deprecated, so you could ask the QML team, why and what alternative you could use.
Solution 5 Implement a JS wrapper for the constructor
This builds upon solution 4. and works even for parameter-less constructors. Instead of registering your helper class directly like this:
engine->globalObject().setProperty("TextFile", engine->newQMetaObject(&TextFile::staticMetaObject));
You could write an additional generator class and a constructor wrapper in JS. Evaluate the wrapper and register this function as the constructor for your class. This wrapper function would pass all desired arguments to the factory method. Something like this:
engine->evaluate("function TextFile(path) { return TextFileCreator.createObject(path);
TextFileCreator is a helper class that you would register as singleton. The createObject() method would then finally create the TextFile object and pass the engine as a paremter:
QJSValue TextFileCreator::createObject(const QString &path)
{
QJSEngine *engine = qmlEngine(this);
return engine->createQObject(new TextFile(engine, filePath));
}
This gives you access to the QJSEngine in the TextFile constructor and you can call throwError().

Connecting slots and signals between a class instance and a dialog within another class instance

I am writing a program in QT, which currently has a GameEngine (data handling) class and a MainWindow (GUI) class.
The single instances of both GameEngineand MainWindow classes are owned by the int main function.
The MainWindow instance has a User Action-button, which will open an instance of a QDialog class called Dialog_UserAction. The instance of this QDialog is owned by the MainWindow, which is also the parent of the QDialog (to disable the MainWindow GUI while the Dialog_UserAction instance is open).
My issue is that many events (signals) need to be connected between the QDialog and the GameEngine instance.
Is there any simple way that I can achieve this?
I have already tried by forwarding the signals from Dialog_UserAction to GameEngine via the MainBoard and vice versa. This works, but it is quite a messy solution for this task.
I have also tried letting the Dialog_UserAction be owned by Main, but I don't know how to react on the User Action Button clicked-event in main context.
Finally, I have also tried letting the Dialog_UserAction be owned by the GameEngine instance, which would the easy solution (except that the MainBoard GUI will not be disabled, while Dialog_UserAction is opened). But, I would really prefer that all GUI related instances were kept out of the GameEngine context.
GameEngine.h:
class GameEngine : public QObject
{
Q_OBJECT
signals:
void someSignalToDialog(void);
public slots:
void on_someSignalFromDialog();
}
Dialog_UserAction.h:
class Dialog_UserAction: public QObject
{
Q_OBJECT
signals:
void someSignalToGameEngine(void);
public slots:
void on_someSignalFromGameEngine();
}
Main.cpp:
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
QApplication::setWindowIcon(QIcon(":/images/MageKnightLogo.jpg"));
GameEngine gameEngine;
Window_MainBoard mainBoard;
mainBoard.showFullScreen();
return a.exec();
}
MainBoard.cpp:
#include "Dialog_UserAction.h"
...
void Window_MainBoard::on_pushButton_enterUserAction_clicked() {
Dialog_UserAction actionDialog(this);
// connect signals and slots here?
if (actionDialog.exec() == QDialog::Accepted)
{
// Send signal with data to GameEngine
}
}
...
So, what I'm really asking is:
Is there any simple way I can setup the signal-slot connections in this setup where I can connect Dialog_UserAction with GameEngine without forwarding the signals in the MainBoard context?
If not, do you have any suggestions on how I could approach this in a better way in general? Thanks in advance.
Since the GameEngine object is a singleton (only one instance exists), you can have the Dialog_UserAction object connect its signals directly to the GameEngine object. You can do that in the Dialog_UserAction constructor.
To get easy access to the GameEngine object, simply add a static member function to it that returns a static GameEngine* member.
GameEngine.h
class GameEngine
{
public:
GameEngine()
{
Q_ASSERT(instance_ == nullptr); // Only one instance allowed.
instance_ = this;
}
static GameEngine* instance() noexcept
{ return instance_; }
private:
static GameEngine* instance_;
};
GameEngine.cpp
GameEngine* GameEngine::instance_ = nullptr;
You can now connect the Dialog_UserAction signals to GameEngine::instance().
So, just for clarification, I ended using the Singleton design pattern as suggested by Nikos C.
But I implemented the class a little differently, and therefore wanted to share this as a standalone answer.
I found that I needed to trigger the constructor of the the object somehow, and figured that this could be done using the so-called (I believe) Lazy Initialization method. Also, the constructor of the class should be private, such that only the instance itself will be able to call this, and thus making sure that the constructor is only called once.
Furthermore, I made the GameEngine::Instance()method as a const static GameEngine*-type in order to let the access to the object be read-only.
GameEngine.h
class GameEngine
{
public:
const static GameEngine* instance() { // Singleton instance reference getter
if (instance_ == nullptr)
instance_ = new GameEngine(); // This triggers the constructor of the object
return instance_;
}
private:
GameEngine(); // The constructor is made private!
};
GameEngine.cpp
// Place this declaration in the top of the file to create the global class instance pointer
// The initial value of the pointer must be nullptr to let the constructor be correctly triggered at the first instance()-call
GameEngine* GameEngine::instance_ = nullptr;
Then in Main and Dialog_UserAction (the clients) the access to the Singleton GameEngine instance is used by creating a const class instance pointer in the each context.
Main.cpp
#include "GameEngine.h"
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
Window_MainBoard mainBoard;
const GameEngine* gameEngine = GameEngine::instance(); // Const pointer to the Singleton instance of the GameEngine class (global object)
QObject::connect(gameEngine, SIGNAL(someSignalToDialog), &mainBoard, SLOT(on_someSignalFromGameEngine));
}
Dialog_UserAction.cpp
#include "GameEngine.h"
// Constructor
Dialog_UserAction::Dialog_UserAction(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog_UserAction) {
ui->setupUi(this);
// Const pointer to the Singleton instance of the GameEngine class (global object)
const GameEngine* gameEngine = GameEngine::instance();
connect(this, SIGNAL(someSignalToGameEngine), gameEngine, SLOT(on_someSignalFromDialog) );
}

Multithreading Design, protect global member in C++

I am writing a c++ app with QT, with a focus at speed optimization.
I want to have a few global objects with read only access for different threads.
Before I open the threads, I have to initialize the global objects and fill them with data.
How I can protect the set functions of my Global Objects, but still have access from the main function?
Example code like it is now:
myClass.h
class MyObjectClass {
public:
void SetSome(const QList<QString> &value);
QList<QString> GetSome() const;
private:
QList<QString> m_myMember;
};
main.cpp
#include "global.h" // some like: extern MyObjectClass g_InihalizedInMain;
#include "anyThread.h"
int main(){
g_InitializedInMain.SetSome() // This Shut work
MyThread thread;
thread.start();
//..
return 0;
}
anyThread.cpp:
#include "global.h"
void thread::run()
{
MyObjectClass newObject = g_InihalizedInMain; //This shut work
g_InitializedInMain.GetSome(); //This shut work
g_InitializedInMain.SetSome(); //This shut not work and give me an error during compile time
newObject.SetSome(); //This shut work
}
I would be happy if you have a few design ideas for me, thanks a lot!
class MyPrivateObjectClass : private MyObjectClass
{
public:
friend void main();
};
extern MyPrivateObjectClass g_InitializedInMain;
Make your global variable static which means only the one source file can access it. You can then provide accessor functions that can read the data from other threads.
For starters, I would try to avoid global variables at all costs.
What you could do instead of global variables is to instantiate a variable in main (either
dynamically, or locally on the stack, depending on your preferences)
and set it in the thread object (this is called dependency injection)
To control setting attributes on MyObjectClass only from main, I can think of 2 options:
Set all of the MyObjectClass attributes via the constructor in main, thus allowing you to remove the setters, but leave the getters. The MyObjectClass would be immutable.
Create a context object that contains all the settable attributes for MyObjectClass. This context object can only be passed into the MyObjectClass constructor. The context object should be created in main, calling the appropriate setters, then passed into MyObjectClass upon instantiation from main. The MyObjectClass class uses these attributes from the context object internally, but doesnt have setters for them. There would of course be getters available on MyObjectClass, that would get the values from the internal context object. The MyObjectClass would be immutable, but this way is a bit more flexible.
I prefer the second option. Here is a code sample:
myClass.h
class MyObjectContext {
public:
void SetSome(const QList<QString> &value);
QList<QString> GetSome() const;
private:
QList<QString> m_myMember;
};
class MyObjectClass {
public:
MyObjectClass(MyObjectContext *context) : context_(context) {}
QList<QString> GetSome() const {return context_->GetSome();}
// Put the rest of the important stuff here
private:
MyObjectContext *context_;
MyObjectClass(); // explicitly stating that the default ctor cant be called
};
main.cpp
int main(){
// creating these objects on the stack, you may need
// to create them dynamically, its up to you
MyObjectContext context;
context.SetSome() // This Should work
MyObjectClass moc(&context);
MyThread thread(&moc);
thread.start();
//..
return 0;
}
anyThread.h
class MyThread : public QThread { // Assuming you're inheriting from QThread
public:
// instead of setting it via the ctor, you could consider adding a setter
MyThread(MyObjectClass *moc) : moc_(moc) {}
void run();
private:
MyThread(); // explicitly stating that the default ctor cant be called
MyObjecctClass *moc_
};
anyThread.cpp
void MyThread::run()
{
moc_->GetSome(); //This should work
// Dont have to worry about the setters, since there are none
// available for the MyObjectClass, which is now immutable
}