c++gccqt5qt5.12

QVector::contains fails with checks against constants


Environment as stated in the tags too:

GCC 64bit, Qt 5.12

I have the following example code:

// test.h

#include <QVector>

class Test 
{
    Test();

    // Same results with QSet
    const QVector<int> things = {
        BANANA,
        RASPBERRY,
        APPLE,
        -2500,
    };

    const int BANANA = -1000;
    const int RASPBERRY = -2000;
    const int APPLE = -3000;
};
// test.cpp

#include <QDebug>
#include "test.h"

Test::Test()
{
    qDebug() << things.contains(APPLE); // false, expected true
    qDebug() << things.contains(-3000); // false, expected true
    qDebug() << things.contains(-2500); // true, expected true
}

I don't understand if I've done something wrong in the definitions or I encountered a bug in Qt.


Solution

  • Seems I was trying to use constant variables not defined yet

    // test.h
    
    #include <QVector>
    
    class Test 
    {
        Test();
    
        // Moved them above QVector
        const int BANANA = -1000;
        const int RASPBERRY = -2000;
        const int APPLE = -3000;
    
        const QVector<int> things = {
            BANANA,
            RASPBERRY,
            APPLE,
            -2500,
        };
    };
    
    // test.cpp
    
    #include <QDebug>
    #include "test.h"
    
    Test::Test()
    {
        // Now the tests pass as expected
        qDebug() << things.contains(APPLE); // true, expected true
        qDebug() << things.contains(-3000); // true, expected true
        qDebug() << things.contains(-2500); // true, expected true
    }
    

    Not a bug in QT!