How to use QVector at or operator[] to get a pointer to the element

c++, qt

Solution

A `T&` value is not a copy, it is a reference.

References look a lot like pointers : they are light, and can be used to modify the underlying object. Only, you use them with the same syntax as direct objects (with dots instead of arrows), and some other differences you may want to check out in the article.

To edit an object currently inside the Vector, you can use for instance `vector[i].action();`. This will call the action() method from the object inside the vector, not on a copy. You can also hand over the reference to other functions (provided they take reference arguments), and they will still point to the same object.

You can also get the adress of the object from a reference : `Object* pObject = & vector[i];` and use it as any pointer.

If you really need pointers to objects, you can also use a Vector of pointers : `QVector<Object*> vector;` However, this requires you to handle creation / destruction, which you don't need with a Vector of objects.

Now, if you want a pointer to the Vector itself, just do `QVector<Object> *pVector = &vector;`

Problem

I would love to get a pointer to a `QVector` element so I can use that object elsewhere however the `at()` method gives me a `const T&` value and the `operator[]` gives me a `T&` value. I'm confused on how to use these to get a pointer so that I will use the same object instead of using a copy constructor.

Original source