1

Surprisingly code below runs in debug/release mode without any crash. How it's possible ? Am I missing something ?

std::queue<int> queue;
queue.emplace(1);
int& a = queue.front();
queue.pop();
std::cout << a << std::endl;
a = 100;
Anand Shah
  • 133
  • 10
  • Does this answer your question? [C++ std::queue::pop() calls destructor. What of pointer types?](https://stackoverflow.com/questions/2002282/c-stdqueuepop-calls-destructor-what-of-pointer-types) – Luca Apr 05 '20 at 14:12
  • Dangling references and pointers are never guaranteed to crash your program, they just *might*. In this case most implementation won't crash because `int` is a trivial type and the underlying `deque` memory is still there. That's part of why dangling bugs are so insidious. – Zuodian Hu Apr 05 '20 at 14:15
  • `int`s aren't actually destroyed by their destructor. The destructor does nothing and the integer hangs around in limbo until something else is given its memory. – rici Apr 05 '20 at 14:15
  • 1
    This fragment exhibits undefined behavior, by way of accessing an object after its lifetime has ended. "Seems to work" is one possible manifestation of undefined behavior. – Igor Tandetnik Apr 05 '20 at 15:08

0 Answers0