0

I have a code like this in C++:

#include <iostream>
#include <deque>
#include <type_traits>

using namespace std;

int main()
{
    deque<int*> myDeque;
    int a = 10, b = 20;
    myDeque.push_front(&b);
    myDeque.push_back(&a);
    int *const &r = myDeque.back();
    myDeque.pop_back();

    cout<<is_reference<decltype(r)>::value<<endl;
    cout << r << endl;
    cout << *r << endl;

    return 0;
}

Basically what I did is using a reference to the previously last element in the deque that has been deleted. However, the compiler reports no error and the behavior is not undefined. Could someone explain to me why this works? Thanks in advance!

  • How can you determine whether a behavior is undefined if the observed behavior is "it works"? Working as expected is one possible outcome of undefined behavior, so just from observation you can never rule out undefined behavior, only confirm it. - "I can't see any undefined behavior" is therefore never a valid statement to make. In this case you do have undefined behavior which just happened to manifest itself in working normally in the few instances that you saw. – CherryDT Jun 25 '21 at 17:31
  • 4
    The behavior _is_ undefined. "Looks like it works" is one of many possible outcomes for undefined behavior. – Mooing Duck Jun 25 '21 at 17:31
  • *However, the compiler reports no error and the behavior is not undefined.* C++ is not a nanny language. It relies on the programmer not to make these kinds of mistakes. It gives you enough rope to shoot yourself in the foot. In this particular case, the bullet didn't even hurt. – Eljay Jun 25 '21 at 17:47
  • Implied in freeing a variable is a promise not to use that variable anymore. If you break that promise, that's on you. Closely related topic: [Can a local variable's memory be accessed outside its scope?](https://stackoverflow.com/questions/6441218) – user4581301 Jun 25 '21 at 18:21
  • Another side note: Code is not a list of instructions to be executed by a computer. It is a description of behaviours you want a program to have. The compiler's job is to read the code, interpret the behaviour, and generate the list of instructions to be executed by a computer. If you specify behaviour that is undefined, the program behaviour is undefined and the compiler can and will do whatever it wants. Usually it takes the path of least resistance and assumes you didn't screw up and very often this makes a broken program look like it worked. – user4581301 Jun 25 '21 at 18:28

0 Answers0