r/cpp_questions • • 2d ago

OPEN why doesn't local variable reference the element of the vector

float current = 0.0f;

WrapPanel::Line& currentLine = lines.emplace_back();

currentLine.first = 0;

for (auto* child : flowChildren) {

UI::Size desired = child->desiredSize;

if (desired.width + current > primaryLimit && currentLine.count != 0) {

size_t count = currentLine.count;

// WrapPanel::Line* a = &lines.emplace_back();

//lines.emplace_back();

//currentLine = lines.emplace_back();

lines.emplace_back();

currentLine = lines[lines.size() - 1];

currentLine.first = count;

currentLine.first = 356;

//debug point here

}

the variable 'first' of last element of std::vector<WrapPanel::Line> lines should be '356'.

currentLine acts like it creates local variable and references it after executing first "if (desired.width + current > primaryLimit && currentLine.count != 0)" when " currentLine = lines[lines.size() - 1];".

the value in currentLine changes but not the value in 'lines'.

my problem is at this line "currentLine = lines[lines.size() - 1];"

it should reference last element of 'lines' but it doesn't.

0 Upvotes

9 comments sorted by

16

u/GoatyGoY 2d ago

You acquire a reference to a point in the container, then push more things to that container. This at some point triggers a reallocation to the underlying data storage, which in could result in the data being moved. The reference you made is now stale, and by using it, according to C++ standard rules, your cat is now pregnant even if you don’t have a cat.

(Note- this is exactly the sort of issue that motivated the invention of rust; so the compiler could tell you this before you get weird runtime behaviour)

7

u/CowBoyDanIndie 2d ago

You cannot reassign a reference. Your currentLine = isn’t assigning a value not changing the reference

5

u/SoerenNissen 2d ago

TL;DR:

If you want to track a specific object in a vector, you have to store the index, not a reference/pointer/iterator into that vector.

Longer:

The term to google is "iterator stability" but the short story is that vector sometimes moves objects around, particularly especially when the vector grows in size.

https://en.cppreference.com/cpp/container/vector

Iterator invalidation

OperationsInvalidated
......
push_back, emplace_backIf the vector changed capacity, all of them. If not, only end().
......

Your first emplace_back does give you a valid element that you can reference.

When you do the second emplace_back, the elements might all go elsewhere in memory, rendering pointers/references/iterators into the vector invalid.

2

u/Kadabrium 2d ago

You first pointed currentLine at the first item, then resized the vector so it now points to invalid memory, then copy assigns a new item's contents into this invalid spot?

2

u/Discordbothost 1d ago

That reference stays bound to the first line. Assignment through it copies a value, and a vector reallocation can leave it dangling. Since your current line is always the last one, use lines.back() when you need it. After emplace_back(), set lines.back().first = count.

1

u/manni66 2d ago

https://en.cppreference.com/cpp/container/vector/emplace_back:

If after the operation the new size() is greater than old capacity() a reallocation takes place, in which case all iterators (including the end() iterator) and all references to the elements are invalidated. Otherwise only the end() iterator is invalidated.

Edit:

A deque doesn't invaliate it's references.

https://en.cppreference.com/cpp/container/deque/emplace_back

All iterators (including the end() iterator) are invalidated. No references are invalidated.

1

u/Independent_Art_6676 2d ago

use the index. If your item is at location [42] now, then 10 min from now after 5 resizes and a move/copy it will still be right there at location 42. Pointers, references and the like into a vector is a footcannon waiting on a trigger pull. Indices into vectors (and C arrays and pointer blocks and so on) can replace pointers/references entirely for most uses.

1

u/tangerinelion 1d ago

currentLine = lines[lines.size() - 1];

Meaning, copy the last entry in the vector to wherever in memory currentLine pointed to when it was created. At best, that's lines[0] = lines[lines.size() - 1]. At worst, you're writing to random space in the heap.

If you want to go down a rabbit hole, change currentLine to std::reference_wrapper<WrapPanel::Line>

1

u/thefool-0 14h ago

What is the best scope for 'currentLine'? Is it meant to refer to one of the vector items across loop iterations or is it a convenience within the scope of one loop interaction to be able to access the item you just pushed?  If the latter then declare and assign it within the scope of the loop.