Sunday, September 4, 2011

Simple Singleton explanation

Hi there people,

I just spent one day trying to figure out why my C++ destruction sequence was creating a resource leak... This morning I noticed it came from one of my Singleton, the one behaving as my database manager.

So people, please be careful when using the Singleton Pattern, esp. when you access resources such as connections, or files.

Here is the thing:

In most cases, you can create a static class member pointing to the instance of your Singleton. This way is really easy to use but generates leak because the destructor is not clearly called. In fact, the memory de-allocation will be done by the OS once you exit your application. Here is the usual code.

// singleton.h
class Singleton
{
public:
    static Singleton* getInstance();
    // Other functions if needed
private:
    Singleton();
    ~Singleton();
    static Singleton* _singletonInstance;
};

// singleton.cpp
#include "singleton.h"

Singleton *Singleton::_singletonInstance = NULL;

Singleton*
Singleton::getInstance()
{
    if(!_singletonInstance){
        _singletonInstance = new Singleton();
    }
    return _singletonInstance;
}

Singleton::Singleton()
{
    // Do what you have to do
}

Singleton::~Singleton()
{
    // Do what you have to do
}

Note: you can see I'm using the lazy initialization to create the instance of my Singleton.

Anyway, this is a very easy and convenient way to have a global and unique instance... Of course, this assume that you do not really need to care about your singleton anymore.

However, if you really need the destructor to be called (e.g. to close a stream) then, it's better to have a simple static variable (no need to check its existence either, it will be created once and for all at the beginning of the application). In this case you can be sure that the destructor will be called. Here is the code:

// singleton.h
class Singleton
{
public:
    static Singleton* getInstance();
    // Other functions if needed
private:
    Singleton();
    ~Singleton();
    // No static class member here !
};

// singleton.cpp
#include "singleton.h"

Singleton*
Singleton::getInstance()
{
    static Singleton _singletonInstance;
    return &_singletonInstance;
}

Singleton::Singleton()
{
    // Do what you have to do
}

Singleton::~Singleton()
{
    // Do what you have to do
}

Of course, you can also do something like this if you want:

Singleton*
Singleton::getInstance()
{
    Singleton* pSingleton = NULL
    static Singleton _singletonInstance;
    pSingleton = &_singletonInstance
    return pSingleton;
}

Anyhow, this second way is much better in the case of a destruction sequence which needs to be clear. In fact, this solved my memory leak problem since with this second version of the Singleton, my destructor was correctly called and the connection to the database was correctly closed.

For your interest, this 2nd case is also called the Meyers' implementation of the Singleton, whereas the 1st one is the GoF implementation.

I hope it can be useful for some of you.

Saturday, September 3, 2011

ListModel in C++ exposed to QML

Hi there people,

I have been working a lot lately on my master thesis and I'm currently developing the prototype of my system. It's getting bigger and bigger, mixing Qt/C++ and QML/Javascript. So far, it's working like a charm.

One interesting behavior of my system is how my system is handling data. Indeed, I needed QML ListModels for my QML UI but I also needed some persistence... So of course I created a database... but since I need to access the database from the C++ side, I couldn't really use the Offline Storage capability of QML since the database generated in this case is randomly named... This would have been quite time wasting to try to access it... So, instead, I create my database with a database manager class written in C++. This database is a simple SQLite database.

At start up, I create several C++ ListModels which are populated from the database and that I link to the instance of the QMLApplicationViewer, this way I can access their data from my QML ListViews and GridViews. The C++ ListModel class that I use, is taken directly from here.

I owe Chris a big big thank for providing this implementation of a ListModel and for giving an example showing how to use the stuff. So Chris, if you read this blog entry, THANKS A LOT!!! :)

I will not explain how this works, Chris is doing that quite well on his own. Just check the given link. But, here comes the why of this blog entry. The implementation provided by Chris is somehow limited. In fact some interesting functionality which are provided in a normal QML ListModel such as count or get() are missing. I guess he let that task for us, or maybe he just didn't think someone would need it.

In my case, I needed to split one of these ListModel in 3 different sub models... I tried to use the QSortFilterProxyModel class but this didn't work... So I came up with another way to do it.

As you might all know (or might know soon by checking this link), when you create a class which is meant to be exposed to QML, you can provide functions which can be called from QML by giving the Q_INVOKABLE flag and QVariant can be understood by QML/Javascript. Also you can provide some variables which can be read from QML by creating a Q_PROPERTY. For the case of my exposed ListModel, I needed the count value and the get() functions, so I made them and here is the code to add to Chris's class:

In the .cpp
QVariant ListModel::get(int row)
{
    ListItem * item = m_list.at(row);
    QMap<Qstring, Qvariant> itemData;
    QHashIterator<int, Qbytearray> hashItr(item->roleNames());
    while(hashItr.hasNext()){
        hashItr.next();
        itemData.insert(hashItr.value(),item->data(hashItr.key()).toString());
    }
    // Edit: 
    // My C++ is sometimes a bit rusty, I was deleting item... 
    // DO NOT delete item... otherwise you remove the item from the ListModel
    // delete item;
    return QVariant(itemData);
}

To get the count.

In the .h
public ListModel : public QAbstractListModel
{
    Q_OBJECT
    Q_PROPERTY( int count READ getCount() NOTIFY countChanged())

public:
    ...
    int getCount() { this->count = this->rowCount(); return count; }
    Q_INVOKABLE QVariant get(int row);
    ...
private:
    ...
    int count;
    ...
};

The get() function will create a QVariant which is like a Javascript object. So you can have later in your Javascript something like:

function useCppModel(){
    // We can check the number of item in our C++ Model now
    for(var i = 0; i < model.count; i++){
        // Here you use the get function declared as invokable
        // It's just like a real ListModel now ;)
        var item = model.get(i);
        // Now, you can then access the content of your item like item.property
    }
}

That's pretty much my addition to what Chris provided and this might inspire/help some of you. I hope you enjoyed. Sorry, if I'm not doing a complete tutorial, but I do not have much time.

P.S.: By the way, I'm now QtAmbassador. Yeah~ :D

EDIT: I corrected the bug with the first C++ code snippet.