Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using delete on pointers passed as function arguments

Tags:

People also ask

How pointers are passed as function arguments?

Pass-by-pointer means to pass a pointer argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the variable to which the pointer argument points. When you use pass-by-pointer, a copy of the pointer is passed to the function.

Can I use a pointer after delete?

Yes, it's totally fine to reuse a pointer to store a new memory address after deleting the previous memory it pointed to.

What happens to pointer after delete?

The address of the pointer does not change after you perform delete on it. The space allocated to the pointer variable itself remains in place until your program releases it (which it might never do, e.g. when the pointer is in the static storage area).

Does delete destroy the pointer?

Yes, it destroys the object by calling its destructor. It also deallocates the memory that new allocated to store the object. Or does it only destory the pointer? It does nothing to the pointer.


Is it okay( and legal) to delete a pointer that has been passed as a function argument such as this:

#include<iostream>

class test_class{
public:
    test_class():h(9){}
    int h;
    ~test_class(){std::cout<<"deleted";}
};

void delete_test(test_class* pointer_2){
    delete pointer_2;
}

int main(){
    test_class* pointer_1;

    while(true){
        pointer_1 = new test_class;

        //std::cout<<pointer_1->h;

        delete_test(pointer_1);
    }
}

This compiles fine now, but I just want to make sure it'll always be that way.