Thursday, August 10, 2023

Const QMap Reference in C++

So recently I was helping a co-worker with one of his stories and one of the architects suggested that he could benefit from using QMaps to solve the issue he was having.  I know my C++ and most times I can think what the compiler is doing behind the scenes but the following I had a fundamental misunderstanding about how references work.

#include <QCoreApplication>
#include <QMap>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    const QMap<int, int> three = {{0, 3}, {1, 3}, {2, 3}};
    const QMap<int, int> two = {{0, 2}, {1, 2}};
    const QMap<int, int> one = {{0, 1}};
    const QMap<int, int> &cur = three;

    cur = three; // compiler complains

    qDebug() << cur.size() << "\n";

    cur = two; // compiler complains

    qDebug() << cur.size() << "\n";

    cur = one; // compiler complains

    qDebug() << cur.size() << "\n";


    return a.exec();
}
As you can see above re-assigning the reference is not allowed.  I think after many years of working with the language there are times where I forget the fundamentals, but there is a little more happening here.
When you make QMap const you are saying that the copy constructor is not enabled.  This is what is actually happening in this case with the reference cur.  So how do you solve this problem?
Well one of the easiest ways is that if you must have some set of N constant maps then you can use a const pointer to QMap.  But then that adds the overhead that now you must ensure that pointer is not null, which is why I think my first approach to this problem my brain thought about was to use a reference.

No comments: