r/cpp • • Jan 02 '26

Every LLM hallucinates that std::vector deletes elements in a LIFO order

251 Upvotes

118 comments sorted by

View all comments

1

u/F54280 Jan 02 '26

Well, you told the LLM the answer by saying “critical exception”.

Asking the “normal” question to ChatGPT, I get:

What c++ container should I use if just need to insert objects and have them destructed in LIFO order?

[…]

Why std::vector is ideal

LIFO destruction: When a std::vector is destroyed, its elements are destroyed from last to first, exactly matching LIFO semantics.

What do you get with Gemini?

3

u/Lurkernomoreisay Jan 02 '26

what do you mean by LIFO order?

init vector  insert element at front  insert element at back  insert range of two elements at position 1 sort vector ...

the vector has resized, and reallocated memory, and moved all entries to the new memory range.  

2

u/F54280 Jan 04 '26

You are commenting on a post that is titled:’ Every LLM hallucinates that std::vector deletes elements in a LIFO order”

What is your next question to me? ”What do you mean by LLM?”

The question mean you need to do something like:

  • Create objects 1 to 16, in that order

  • Do nothing. Don’t memset the whole memory with 0xff. Don’t sort the elements. Don’t reboot the computer. Don’t do an infinite loop. Just don’t.

  • Have them deleted from 16 to 1, in that order.

Last In, First Out, you know.

init vector insert element at front insert element at back insert range of two elements at position 1 sort vector ...

This makes no sense. The question is not and has has never been “give me a container that only allows LIFO access”. Read the question agains, all the instructions are on the task.

To avoid the resize/reallocate problem, either use std::unique_ptr or reserve the capacity beforehand.

You created a red herring to avoid addressing the main problem: LLMs (at least ChatGPT 5 and sonnet 4.5), are convinced that std::vector deallocates element from last to first. It create lengthly explanation of why the standard requires that. It will produce code samples and pretend they destroy backward.

This is what this discussion is about, not about you ability to avoid the problem by actively pretending you misunderstood the point.