0

I'm new in C ++.

And I'm trying to understand some things.

Among the use of the C++ delete operator. what I have learned is that: it deallocates the memory block pointed to by ptr (if not null), releasing the storage space previously allocated to it by a call to operator new. So I expect that if the pointer refers to the memory block of an object, it calls the destructor method of the object and deletes the object. So I wrote this code to test this:

#include <utility>      // std::forward
#include <iostream>     // std::cout
using std::cout;
using std::endl;
#include <string>
using std::string;

class Apartment;

class Person {
    public:
        Person(string n){
            cout<<"init Person"<<endl;
            name = n;
        };
        ~Person(){
            cout<<"Person : "<<name<<" deinit"<<endl;
        };
        Apartment *apartment = 0  ;
        string name;
};

class Apartment {
    public:
        Apartment(string u){
            unit = u;
            cout<<"init appartamt"<<endl;
        };
        ~Apartment(){
            cout<<"Apartamt : "<<unit<<" deinit"<<endl;
        };
        Person *tenant = 0;

        private:
            string unit;

};

this is the main:

int main(){

    Person *emanuele = new Person("Emanauele") ;
    Apartment myAparment = Apartment("unit16C");

    emanuele->apartment = &myAparment;

    myAparment.tenant = emanuele;

    cout<<"delete emanuele:"<<endl;
    delete emanuele;
    emanuele = NULL;

    cout<<myAparment.tenant->name<<endl;
}

And this is the output:

init Person
init appartamt
delete emanuele:
Person : Emanauele deinit
Emanauele // WHY !!!!!

As you can see from the output, after the person object's destructor has been called, the block of memory still contains the information of the person, and it is possible to reach them through the Apartment's pointer via the command:

myAparment.tenant->name

why does this happen?

emacos
  • 541
  • 1
  • 8
  • 17
  • 1
    Why do you expect delete to change the contents of memory? That would be an unnecessary overhead. Dereferencing a deleted pointer is undefined behaviour. – Richard Critten Jan 18 '18 at 20:44
  • 2
    Destruction does not imply that memory ceases to exist or is scrubbed of its contents, merely that it's released for use elsewhere. – Fred Larson Jan 18 '18 at 20:46
  • 1
    You are invoking undefined behavior. Don't dereference deleted pointer. – Ron Jan 18 '18 at 20:46
  • 1
    ”I took his wallet so he can’t be dead” will never hold up in court. – molbdnilo Jan 18 '18 at 20:56

0 Answers0