r/cpp • • Jan 02 '26

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

251 Upvotes

118 comments sorted by

•

u/STL MSVC STL Dev Jan 02 '26

In the future, please post links as link posts, not as text posts. This helps readers.

→ More replies (3)

14

u/Warshrimp Jan 02 '26

I wish the standard didn’t specify an order, it seems to me that relying on the order of destruction would be error prone.

37

u/am17an Jan 02 '26

It doesn't specify an order AFAIK

-11

u/alex-weej Jan 02 '26

I wish the standard mandated random ordering so you absolutely can never depend on it by accident. Systems implying order where there is none leads to nasty outages when that order spontaneously changes!

12

u/YouNeedDoughnuts Jan 02 '26

I don't know about the standard, but I wish compilers typically did things in random order in debug builds. MSVC is nice for using fill patterns for uninitialised variables in debug builds, whereas other compilers are apt to give you 0 initialized memory non-deterministicly but often enough to mask bugs.

5

u/wasabichicken Jan 02 '26

That's this, isn't it?

2

u/Chuu Jan 04 '26

An implementation of the STL that intentionally uses the most perverse but technical legal implementation for all operations would be a fun side project. If google still has 'Summer of Code' projects I can see it as a great project for a student interested in C++.

18

u/AntimatterTNT Jan 02 '26

if you mandate order why not make it one that can be used?

→ More replies (7)

27

u/Chuu Jan 02 '26

I was surprised Gemini would get this wrong, and gave it a very simple prompt to see if it would fail:

I need you to investigate some std::vector<> behavior for me in C++. Assuming we're using a recent version of clang (18+) and libstd++. In the libstdc++ implementation, when a vector is destroyed, in what order are the destructors of the elements in the vector destroyed? Can you write me a very simple C++ program (including a main method) to prove it?

I'm not going to quote the entire response and sample program, but it seems to have passed the test. The first paragraph of the response:

In the libstdc++ implementation (the standard library used by GCC and often Clang on Linux), the elements of a std::vector are destroyed in forward order—from the first element (index 0) to the last element (index $N-1$).

This is an interesting detail because it differs from how local variables on the stack are handled (which are destroyed in the reverse order of their construction). In libstdc++, the destructor calls an internal function std::_Destroy, which simply loops from the begin() iterator to the end() iterator, calling the destructor of each object in sequence.

21

u/Wacov Jan 02 '26

Maybe your question prompted more internal reasoning or web searching that the article author's? E.g. asking it to "investigate" could make it more thorough 

21

u/Chuu Jan 02 '26

I should have looked at what the actual prompt they gave it was. I was reading the article and it stated the following:

This confused me so I posed a simpler question to all leading LLMs, and it seems like they all think std::vector destructs elements from back to front.

Their "simpler prompt" was basically pasting the entire program into the LLM and asking it what it would do. That is . . . not a great way to go about this, and definitely isn't simple.

-7

u/am17an Jan 02 '26

>  That is . . . not a great way to go about this, and definitely isn't simple.

Well my initial try was just asking it to create a container that does what I want, and it made std::vector. This was my attempt at simplifying. Your prompt is kinda data-leakage because it already peppers the prompt with "investigate", so it "thinks" more or does more searches like the other comment said. However while programming you're not constantly testing the LLM about its knowledge.

TBH if a C++ programmer gave that answer in an interview (to my exact prompt) they would not pass. std::vector is the most important container by far and knowing how it's destructor works is essential for understanding how the underlying memory works.

5

u/Chuu Jan 02 '26 edited Jan 02 '26

From you article though, you state:

I recently needed to delete objects in a LIFO manner and employed an LLM to rubber-duck about what would be the best container. All of them said std::vector. This confused me so I posed a simpler question to all leading LLMs, and it seems like they all think std::vector destructs elements from back to front.

Just in general, if I run into something with an LLM that confuses me, I find it best to focus on the specific root of the confusion. And ask for citations/examples which makes it a lot easier to verify. At least from this paragraph the root appears to be the behavior of std::vector<>'s destructor.

Out of curiosity, I decided to just ask Gemini the question directly about how it would design the container and am curious what it would recommend.

I need help finding a suitable container in C++ with some specific requirements: 1. It is to be a "sequence container" that supports random access and insertions. In terms of API and expected behavior, basically identical to std::vector<> except with one critical exception.

2. The critical exception, when this container is destroyed, all elements in the container must be destroyed in LIFO order. Especially note that we cannot assume that items were always added to the front or back of the collection, they might have been inserted in the middle, so the order of destruction might "skip" around the container.

What would you suggest be the best approach here? Are there any existing collections that could be used as a basis for this behaviour? Please be brief.

I'm not going to post the (lengthy) response but in general the answer it gave was along the lines of what I'd expect most people to come up with initially. Essentially a container that needs to maintain two internal containers -- the underlying sequence container and also another collection (some discussion in the LLM response about the choice here) to track ordering.

15

u/mark_99 Jan 02 '26 edited Jan 02 '26

You (and the LLM) are quite correct here to highlight what do they even mean by "LIFO order" given you can insert anywhere in a vector.

This might be one reason why the standard doesn't specify it, as it might coincidently work of you only do push_back only to be caught out when inserting elsewhere.

Some people are keen to latch on to "LLM gets it wrong" posts, but if you can't even formulate your question correctly it's not a good start.

→ More replies (1)
→ More replies (7)

52

u/irqlnotdispatchlevel Jan 02 '26

Making that a failure state in an interview regardless of everything else discussed during the interview makes you a bad interviewer.

32

u/SkoomaDentist Antimodern C++, Embedded, Audio Jan 02 '26

It seems to be a sadly common assumption (including in many conversations in this very sub) that knowing language details is somehow much more important than understanding the problem domain or being capable of succesfully working on complex programs.

11

u/irqlnotdispatchlevel Jan 02 '26

Besides this, failure states are almost never good because interviews are nothing like the day to day work and can be very stressful. It should be expected that even very good candidates will give extremely dumb answers to trivial questions because of this (not that in this case the answer would be dumb, since it makes sense to have a container that behaves like that). That's why it's an hour long, often multi stage, process.

9

u/ReDucTor Game Developer | quiz.cpp-perf.com Jan 02 '26

TBH if a C++ programmer gave that answer in an interview (to my exact prompt) they would not pass

Except they would be correct, it's a valid answer you just gave a terrible question which was open to any order. I certainly hope you are not involved in the interview process because that sort of question should never be in an interview, it's just a gotcha type of question.

5

u/MaxHaydenChiz Jan 02 '26

There are ways to design prompts that will reliably get better answers and fewer halicucinations. Your way isn't one of them (for now). The way he asked it is the way to do it if you want reliable information.

→ More replies (1)

0

u/Serious-Regular Jan 02 '26

prompted more internal reasoning

do you really believe this?

7

u/Sopel97 Jan 02 '26 edited Jan 02 '26

Because it's a completely different prompt. LLMs are not logically consistent, especially in different sessions.

3

u/SlightLocation9 Jan 02 '26

Well, that's a question about specific implementation, not about the standard. Anyway, Gemini still missed one important bit - for trivially destructible types there will be no loop at all.

161

u/Artistic_Yoghurt4754 Scientific Computing Jan 02 '26

In my experience LLMs are (currently) awful at being your language/standard lawyer.

It just hallucinates paragraphs that do not exist and reaches conclusions that are very hard to verify. In particular, it seems to (wrongly) interpolate different standards to conclude whatever it previously hallucinated. I am honestly not sure we need a short blog post for each hallucination we find out...

IMHO, these kinds of questions are kin to the UB in the standard. It works until it doesn't, and let's hope that it was a hard failure that you could notice before shipping for production.

33

u/Zero_Owl Jan 02 '26

Yeah I had quite a "fun" experience where it "quoted" Standard with text it never had. It was actually kinda hilarious when it insisted of Standard having that text.

9

u/SlothWithHumanHands Jan 02 '26

And it’s still very difficult to determine why, like actual bad training data, spelling confusion, training weakness, etc. I’d like the default ‘thinking’ behavior to just go double check sources, so I can guess what I should not trust.

39

u/Ameisen vemips, avr, rendering, systems Jan 02 '26

Because in the end it's still just a probabilistic text predictor.

→ More replies (7)

8

u/Artistic_Yoghurt4754 Scientific Computing Jan 02 '26

I would even give the direct quotes of the standard and it would still rewrite the quote or reach conclusions that I could not verify with my limited human logic.

To be fair, they also help to narrow down the sections of the standard that are relevant to a given (complex) question, so they are not entirely useless.

7

u/cd_fr91400 Jan 02 '26

I never trust LLM for this kind of requests, and I systematically check what they say, but there are numerous cases where the answer is correct. And even when they're not, the answers quite often guide me to the right place when I check or help me in a way or another.

11

u/balefrost Jan 02 '26

Though I'm sure there are layers and layers at this point, fundamentally LLMs are just glorified Markov chain generators. They form sequences of words that, according to their training data, tend to follow each other.

Even if you trained one exclusively on a particular text, it could still take phrases from one part of the text and mash them together with phrases from another part of the text, thus hallucinating quotes that never existed in the text.

4

u/NotMyRealNameObv Jan 03 '26

Because while it has learned how standards are written in the general sense, it has no memory of any actual standard, so it is impossible for it to actually truly quote something.

1

u/CheetahSad8550 Jan 02 '26

Yeah, these kind of hallucinations have been what have kept coding assistants from being pure wins and hold things back a lot. I've run into an issue where it invents a convenient function in a library that doesn't actually exist. While investigating why the code doesn't compile it'll tell me that my library must be out of date and I need to go update it. And only then I'll see that I'm on the latest version and realizing that it's just trying to justify an earlier hallucination with more bs.

AI really needs to be trained that "I don't know" or "the thing you're asking is a lot more work than you think and you should probably seek a different solution" are valid answers but I think with the way that the model fine tuning steps really biases answers towards a "correct looking" solution with not enough verification of if it actually is correct.

1

u/jaaval Jan 02 '26

They tend to work fine if you ask them to read a specific standard and then ask questions about it.

-10

u/[deleted] Jan 02 '26

[removed] — view removed comment

5

u/Artistic_Yoghurt4754 Scientific Computing Jan 02 '26

Like which other one? TBH I am only familiar with the one of C++

1

u/Western_Objective209 Jan 02 '26

It's not even a language lawyer issue, this particular issue is not defined in the spec. If it was defined they probably would have the information

→ More replies (1)

41

u/baudvine Jan 02 '26

Huh, that's weird. I could've sworn that's how it works. Not sure where I picked that up, then (but definitely not from an LLM).

26

u/Chuu Jan 02 '26

I did a little bit of digging in the standard*, and as far as I can tell the order of destruction is unspecified. cppreference.com's specification of the destructor (Destructs the vector. The destructors of the elements are called and the used storage is deallocated) also seems to support this conclusion.

(In the C++20 standard, section 22.2.1 and table 73. Specifically the destructor for containers is specified as "destroys every element of a; any memory obtained is deallocated." and also must run in linear (or better) time.

1

u/The_JSQuareD Jan 02 '26

This seems surprising and problematic. Admittedly, in most cases the order of destruction won't matter, but in some cases it certainly might. Getting inconsistent behavior between implementations here seems like an unnecessary self-inflicted wound. As far as I can tell, there would be no performance penalty for the standard to simply prescribe an order. For std::vector going from back to front seems reasonable (and consistent with arrays). For other containers I think you can also prescribe an order (not necessarily matching the vector's destruction order) that won't incur a performance penalty; e.g., for std::forward_list you'd prescribe that the order of destruction is the forward order in the list.

15

u/CocktailPerson Jan 03 '26

Getting inconsistent behavior between implementations here seems like an unnecessary self-inflicted wound.

Oh, my sweet summer child...

The entire C++ standard is full of self-inflicted wounds like this. This is probably the least egregious example I've seen.

2

u/NotMyRealNameObv Jan 03 '26

Why on earth would the standard be expected to define the exact order that elements in a vector are destroyed?

5

u/The_JSQuareD Jan 03 '26 edited Jan 03 '26

To... standardize behaviors.

Or to give you a less glib answer: the standard defines the order destructors run in when you call delete[]. It is reasonable to expect that it would also define it for the most common library wrapper around a dynamic array.

1

u/kalmoc Jan 03 '26

I'm willing to bet (only a very very small amount of Money) that different compilers already implement this inconsistently and this it can never be fixed due to backwards compatibility concerns.

1

u/Wooden-Engineer-8098 Jan 08 '26

if it matters to you, destroy them in any order you like. why impose your requirements on everyone else?

13

u/ozyx7 Jan 02 '26

I had the same mistaken belief. I think it might because delete[] destructs elements back to front, and array elements are destructed back to front, so it probably would be reasonable to assume that std::vector (which is the typical go-to for replacing those) would behave the same way, but alas, it does not.

6

u/baudvine Jan 02 '26

Oh, yep. I would definitely have assumed that if delete[] does that, then the vector dtor would Obviously work the same because that's the simplest way for things to be. Not quite a footgun, but definitely surprising.

... time to grep a hundred repos for "order", "destruction", "vector" in comments to see where I relied on this

1

u/Wooden-Engineer-8098 Jan 08 '26

why would you assume such nonsense? delete[] doesn't have any of vector's apis for controlling order of construction and destruction

3

u/uraev Jan 02 '26 edited Jan 02 '26

In my first try, gpt-5.2-thinking acknowledged that it was implementation dependent but claimed most implementations would use LIFO.
So I added "I'm building with g++" to see if it would get it right about g++ and Chatgpt decided to just read the code in its internal tooling during its thinking.
It first searched for the pattern '/usr/include/c++/*/vector' using python. Then in its thinking:

I think the destructor probably uses std::_Destroy from bits/stl_construct.h, which might destroy in reverse order. I need to inspect this function more carefully to confirm its behavior. I'll check the file at /usr/include/c++/12/bits/stl_construct.h for more details.

Tried a regex which failed, tried grep on "void _Destroy(" which worked. Based on the code it got:

Okay, so _Destroy_aux destroys in forward order. Given that, the expected output would be "Destruct 1" followed by "Destruct 2." Since g++ is being used, it aligns with the expected forward destruction.

Its funny that it thinks "it aligns with the expected forward destruction" when its first guess was reverse order. Later it did web searches that even found this exact reddit post. It decided:

After reviewing the sources, it seems like libstdc++ isn't explicit about the forward order, but it's clear from inspection of the header for GCC 12. While no citation is needed for this conclusion, I’ll briefly note that the standard doesn’t specify the order of destruction. The answer remains: "Destruct 1" then "Destruct 2."

The chat: https://chatgpt.com/share/6957acb5-7d70-8002-a8e3-6e77a3f0799e
My custom instructions have requests for harder thinking and more searching, which explain why I got a better result than you. I get that you didn't ask for searches/tests on purpose to test hallucinations, but also most people reading this aren't aware that in realistic use cases AIs will just check, and use their tools in smart ways, and so hallucinations are less of an issue.

Edit: I just clicked on the link and can't read the chain-of-thought at all. Is this a new change? I shared chatgpt chats before, and the thinking used to be included.

Edit2: Since the link didn't work, here are screenshots of tool usage on gpt-5.2-thinking: https://imgur.com/a/fn5u2oC

2

u/am17an Jan 02 '26

Haha, that's the exact point I was making about the "Observer Effect", looks like it's fixed faster than I thought it would be :)

> most people reading this aren't aware that in realistic use cases AIs will just check, and use their tools in smart ways, and so hallucinations are less of an issue.

I think most people would be better knowing that LLMs hallucinate rather than thinking with "custom instructions for harder thinking and more searching", they go away

3

u/uraev Jan 02 '26

People definitely need to know about hallucinations, your post is very helpful.

It's just that most redditors already know that hallucinations happen, but don't know that AIs can understand and use information from searches to give better results, or that they can use tools at all. Most of them have only used free AIs that don't take an extra minute to check sources, or do tests, and think AIs aren't that useful.

It's important to both know the issue and how to deal with it, of course.

2

u/CarloWood Jan 02 '26

The "reasoning" text is not reasoning: it is also generated text, word by word, that has been forced to look like reasoning. It has been proven that it is as unreliable and often untrue as any answer it comes up with: fabricated to match a certain goal. Ie if it already knows the answer it will come up with a "reasoning" that ends with the conclusion that the known answer is the answer. This is why chatgpt 6 is going to drop the requirement to think in English: it is not only useless, it probably just hurts the model because now it has to fulfil two goals at once.

1

u/pfultz2 Jan 02 '26

What prompt do you use for custom instructions?

95

u/feverzsj Jan 02 '26

LLMs are worse than good old search engines. It'll even make fake reference to sources with contradictory results.

48

u/totallyRebb Jan 02 '26

They seem great at simulating the type of people who confidently share their dangerous half-knowledge. Dunning-Kruger Sims.

4

u/Serious-Regular Jan 02 '26

clearly they've been "fine-tuned" on hn comments

3

u/Aquatic-Vocation Jan 03 '26

So far, the best use-cases for LLMs I've found are:

  1. a fancy line auto complete, like intellisense on steroids. Sometimes your brain moves faster than your fingers and those moments where I start typing out a loop and it auto completes the exact few lines I was going to type makes me feel like I'm seeing through the matrix.
  2. a fancy rubber ducky.

2

u/drbazza Jan 05 '26

If you don't have any, writing unit tests for existing (simple) code works well to 'fossilize' current behaviour before a big refactor.

And... refactoring beyond what's offered by IDEA/CLion works reasonably well.

1

u/PharahSupporter Jan 02 '26

Humans can do this also, doesn't mean the tool is useless, just have to be cautious with it.

4

u/Aaron_Tia Jan 03 '26

At some point if the tool shot yourself in the foot from time to time we should be able to state that it is a poorly efficient tool.

1

u/heyheyhey27 Jan 03 '26

Says a C++ programmer...

1

u/Aaron_Tia Jan 03 '26

Yes. I never fought against people saying "for security application rust is better because it prevent most c++ issues". Here the problem is "too many bullshit answered in every possible context"

1

u/heyheyhey27 Jan 03 '26

But it doesn't answer bullshit in every possible context. For example it's great when working off of code samples, and understands language syntax very well. I use it to mock up tricky template and concept stuff, or to find syntax errors in my code in those few cases where my eyes glaze over and I can't find it.

1

u/[deleted] Jan 02 '26

sadly search engines are horseshit and typing simple things could yield results that are barely related

9

u/Inevitable-Ad-6608 Jan 02 '26

For your initial question "Can you tell me a container in C++ which would delete elements in an LIFO order on destruction?" Perplexity already states: "There is no standard C++ container that guarantees destroying its elements in LIFO order on destruction." and refers of this very reddit post!

12

u/philclackler Jan 02 '26

How can we help poison them to do this more so we can still have jobs in the future

1

u/_x_oOo_x_ Jan 02 '26

Apparently there's a prominent StackOver flow answer that these LLMs got trained on, so that would be one way...

3

u/_x_oOo_x_ Jan 02 '26 edited Jan 02 '26

Grok (even 4.1 Fast) gets it right, Perplexity Sonar also kind-of does, first it tells you it's back-to-front but then says some implementations do that but the standard leaves the order unspecified. Also tested Claude Sonnet 4.5, Zhipu GLM 4.7, Google Gemini 3 Pro, which get it wrong

Edit: GPT-4-turbo-2026 Deep Research also gets it right: https://chatgpt.com/share/69582d5c-a4d0-8009-9730-528f010c7eaa

5

u/pwab Jan 02 '26

This looks like an attempt to “train” future LLM’s with blog posts. This is both reasonable and frightening. If i extrapolate this into absurdity, I’m imagining Russia furiously poisoning the world’s knowledge base to steer LLM’s into directions that cause chaos.

The current conception of these tools rests on unstable foundations.

2

u/OkResource2067 Jan 02 '26

Also, recently tested chatgpt with a question about a detail of the Chernobyl accident, and it confused up/down, hot/cold, and before/after in several places in the response 😅

2

u/DatBoi_BP Jan 02 '26

How did we let this happen

4

u/BeigeAlert1 Jan 02 '26

I have nothing but utter disdain for LLMs, but in fairness, I thought that was how it worked too... and it kinda makes more sense to me that way.

3

u/victotronics Jan 02 '26

"Putting this post out on the internet might have the effect of correcting this mistake in future iterations." I'm conflicted wether that's a good idea.

2

u/korri123 Jan 02 '26 edited Jan 02 '26

For me with extended thinking on Claude Opus 4.5 gets it right

6

u/ShelZuuz Jan 02 '26

It is implementation defined.

1

u/Liam_Mercier Jan 02 '26

I tried this with gemini 3.0 fast and it did not hallucinate the actual print statements, but chatgpt does for whatever the model is by default.

Amusingly, gemini 3.0 still says the operation is LIFO.

1

u/Oster1 Jan 02 '26

So in a way LLM was correct because C++ hasn't specified the destruction order in the standard and OP thinks the order is wrong because it was something else than what his own compiler generated?

1

u/Kiore-NZ Jan 02 '26

It's highly likely that the LLMs picked it up from "common sense" interpretations of how it works.

[Rant] It may also be the way that all major STL implementations have implemented it, but if a developer wants their code to be portable across different compilers or different machines, including ones that will be created several years in the future, they need to only rely on things that are specified in the standard. As u/Chuu pointed out here a few hours ago, the standard doesn't specify the order of running destructors on elements of a container. Any code that relies on the order of destruction may break when ported to a different machine, a different compiler or possibly even a different version of the same compiler. This is another example of LLMs giving unsafe advice.[/Rant]

There's not much I miss about Usenet, but comp.lang.c used to have a beautiful expression for the dangers of using constructs with undefined behaivour the compiler may "make demons fly out of your nose" on the logic that when encountering it the compiler is free to do anything it likes.

A more achievable response to undefined behaivour was in early versions of GCC where any use of the #pragma directive would cause the compiler to stop compiling and attempt launch one of 3 different games (hack, rogue or hanoi) with a fallback to

fatal ("You are in a maze of twisty compiler features, all different");

By version 1.35 from 1989 this code had been commented out.

3

u/Chuu Jan 02 '26

Kind of a nitpick, but an important nitpick, but this isn't undefined behavior it's unspecified behavior. The state of the program before and after the destructor runs is well defined.

1

u/[deleted] Jan 02 '26

The only more or less reliable way I got an AI to work is giving it the standard specification document and ask directly (the best one for this is NotebookLM) but again, this is for knowledge/reference not programming at all. 

1

u/azswcowboy Jan 03 '26

note the complexity…

Sure, that’d be great if they gave some sort of confidence judgement in their answer. The thing is, it’s actually not complex in this case as it’s entirely specified. The answer is here: http://eel.is/c++draft/container.requirements#container.reqmts-24. That’s the general answer for all containers, unless they specify something further. They mostly don’t. So the only complexity is you have to understand the words that say vector complies with that paragraph unless specified otherwise. Same with all the rest.

The reason LIFO is confusing possibly for the LLM is there are no containers in the standard that have LIFO behavior (queue and stack are adaptors).

I think it should

I don’t think you want that actually. There’s possibly optimizations left on the table. For one, any type with a trivial destructor doesn’t need it called at all - just deallocate.

If you need that behavior wrap it. That’s what I was getting at with my pointer to erase. There you define the order

template <class T> MyVec {
    std::vector<T> vec;
    public:
    ~MyVec() { std::erase( vec ); }
};

1

u/ppppppla Jan 03 '26

Here I am reading LLM as LLVM and being really confused by the title.

1

u/ShelZuuz Jan 02 '26

Opus 4.5 gets this right for me on multiple tries. I think the OP was set to Sonnet (which does get this wrong).

-4

u/ReDucTor Game Developer | quiz.cpp-perf.com Jan 02 '26 edited Jan 02 '26

The LLM is correct, the standard does not specify the order. Your prompts did not give it any guidance that required it to give you the answer you desire (a specific compiler version and standard library).

Why you would even ask an AI these sorts of questions is beyond me.

1

u/am17an Jan 02 '26 edited Jan 02 '26

> The LLM is correct, the standard does not specify the order.

The LLM doesn't say that though, it says they are destroyed from back to front?

> Why you would even ask an AI these sorts of questions is beyond me.

What sorts of questions should I ask, ReDucTor?

4

u/ConcertWrong3883 Jan 02 '26

> What sorts of questions should I ask

Simple childish ones, like the number of Rs in strawberry, not deeply technical ones!

-4

u/OkResource2067 Jan 02 '26

Vectors do have a stack interface via back, push_back and pop_back. And runtime complexity is good. They are perfectly adequate stacks except that they have like 50 methods, which means that they can never rise to the level of good. Easy to wrap, of course.