grevi
grevi

Reputation: 23

Deleting an object by function in C++

I'm a bit curious about a pointer's behaviour in C++. So I have this little program to test out and unfortunately it run well.

#include <iostream>

class Test{
    public:
        Test(){
            std::cout<<"Test Created!\n";
        }
        ~Test(){
            std::cout<<"Test Destroyed!\n";
        }
};

void destroyer(Test* T){
    Test* temp = T;
    delete temp;
}

int main(){
    Test* ptr = new Test();
    destroyer(ptr);
}

And it gives in return

    Test Created!
    Test Destroyed!

And I draw the conclusion that when we delete a pointer, actually it just deletes the object that the pointer refers to, not the variable itself (variable pointer will automatically deleted at the end of program, same as other primitive data type). Is my thought about this true?

Upvotes: 2

Views: 856

Answers (3)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123566

Colloquially we say "delete the pointer" when we write

 delete x;

However, this isnt quite accurate. What is deleted is the object pointed to by x.

And i have conclusion that when we delete pointer, actually it just delete the object that pointer refer to not the variable itself (variable pointer will automatically deleted at the end of program, same as other primitive data type). Is my thought about this true?

Yes.

In practice the inaccuracy mentioned above is just fine because after deleting the object the pointer value cannot be used without invoking either implementation defined or undefined behavior and that also affects other pointers to the same object:

   int* x = new int(42);
   int* y = x;
   detele x;
   std::cout << x << y;   // implementation defined
   std::cout << *x << *y; // undefined
   x = new int(42);       // OK

For details see here.

Upvotes: 1

Caleth
Caleth

Reputation: 63402

delete is an operator that looks at the object pointed to by the pointer object. The pointer variable is still a local value whose lifetime is tied to the scope it is declared in.

You have 3 pointer objects, with differing lifetimes. Only ptr in main lasts to the end of the program. T and temp only exist during destroyer.

Upvotes: 1

Greg Hewgill
Greg Hewgill

Reputation: 994947

Yes, the delete operator only calls the destructor and frees the memory occupied by the object that the pointer points to. The pointer itself is a local variable like any other and cannot be (and does not need to be) deleted.

It may be worth noting that calling delete ptr; does not change the value of ptr, so after deleting the pointer ptr would point to memory that has been deallocated. It would be undefined behaviour to access that memory after deleting it.

Upvotes: 5

Related Questions