Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

std::vector reference error C2440



  • Hi there,

    I'm using Qt 5.9.7 with Visual Studio 2017 64bit compiler or alternative Visual Studio 2017 with Qt Viusal Studio Tools 2.2.2 programming Windows desktop application.

    I got a problem in Qt using vector references.

    The code below runs fine as pure Visual Studio 2017 C++ console application.

    But the same code gives the C2440 error message if it is compiled in Qt Creator as C++ console application (without QT), as Qt console application or as simple QWidget application. The same happens if the code is compiled in Visual Studio as Qt application.

    //
    #include <iostream>
    #include <vector>
    
    int main()
    {
        std::vector<int> vec { 0,1,2,3 };
        for (auto& v = vec.begin(); v != vec.end(); v++)
        {
        }
    
        return 0;
    }
    

    The error message is:
    error C2440: "Initialisation": "std::_Vector_iterator<std::_Vector_val<std::_Simple_types<_Ty>>>" can't be converted to "std::_Vector_iterator<std::_Vector_val<std::_Simple_types<_Ty>>> &"

    And in the code the first "vec" in the loop is marked red.

    Without using reference the code runs fine on all platforms.
    But I want to use reference because the code is in a performance critical part of my application.

    So why does the code run fine as Visual Studio C++ console application and doesn't compile in Qt? What's wrong?

    Regards,
    mireiner



  • Hi
    Do you have "CONFIG += c++11" in your pro file?


  • Lifetime Qt Champion

    @mireiner Remove & after auto. begin() returns an iterator and not a reference to an iterator.



  • Yes I got
    CONFIG += console c++11
    and tried also
    CONFIG += console c++1z
    and
    QMAKE_CXXFLAGS += -std:c++latest
    all with no luck :-(


  • Lifetime Qt Champion

    @CKurdu As far as I know this is not needed with Microsoft compiler.



  • @jsulm

    Sorry I mainly used ranged based loops and not very often iterators. So let me ask again to make sure:

    You mean: Reference can't be used here?
    Is there any way to use iterators with reference at all? How does the code look like then?


  • Lifetime Qt Champion

    @mireiner an iterator is a reference (or a pointer, to be more specific)...


Log in to reply