0

I am learning C++ and I am have written some code to get some experience with manually creating and removing objects. I don't think I fully understand the semantics of delete because the print statement still prints 3 and I believe it shouldn't.

Code

#include <iostream>

class Test {
public:
    int x;
    int y;
};

using namespace std;

int main() {
    Test t1;
    t1.x = 1;
    t1.y = 2;
    cout << t1.x << endl;
    cout << t1.y <<endl;

    Test *t2 = new Test();
    t2->x = 3; t2->y = 4;
    cout << t2->x << endl;
    cout << t2->y <<endl;
    delete t2;

    cout << t2->x << endl;
}

Output

joel-MacBook-Air:src joel$ ./test 
1
2
3
4
3

Please could you explain why it prints 3 at the very end? My knowledge is that it shouldn't print 3 as I deleted the object.

user3199023
  • 433
  • 2
  • 8

1 Answers1

7

It is undefined behaviour to access an object after it has been destroyed. Your program could do anything. It just so happens that you still get the value 3.

4.1/1 [conv.lval] A glvalue of a non-function, non-array type T can be converted to a prvalue. [...] If the object to which the glvalue refers is not an object of type T and is not an object of a type derived from T, or [...], a program that necessitates this conversion has undefined behavior.

Accessing a member of an object necessitates this conversion.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • As the memory (luckily) hasnt been touched yet and the pointer still points to the old location – Sebastian Hoffmann Jan 18 '14 at 13:55
  • @Paranaix I didn't say that because I don't want the asker to think they can rely on this "luck". – Joseph Mansfield Jan 18 '14 at 14:01
  • Yeah ofcourse, but I think its also important to tell the OP why it still works and not just telling him "Undefining behaviour, dont do it and dont think about it" – Sebastian Hoffmann Jan 18 '14 at 15:03
  • @Paranaix The thing is, you can't even be sure that it is "still working" when you get the value 3. It could be that the memory contains something totally different now, but that the number of bytes corresponding to an `int` at that address happens to contain the value 3 by coincidence. That is why it is more accurate to say that it is undefined, rather than try to make statements about why it has a certain value. – JBentley Jan 18 '14 at 15:30
  • @JBentley I know what unexpected behaviour means, buts its though very very likely that my explanation applies to this case. This is by no means a reasoning to rely on this behaviour, dont missunderstand me, but its IMO very important to understand what happens under the hood. Myself works on RE projects and understanding what `delete` actually/usually does is quite relevant there. – Sebastian Hoffmann Jan 18 '14 at 15:45
  • Thank you @sftrabbit for a clear, concise answer. – user3199023 Jan 18 '14 at 16:07