Search code examples
c++memory-managementnew-operator

Using delete on pointers passed as function arguments


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.


Solution

  • It will always compile without error.

    Whether it's a good thing to pass a pointer into a function and delete it in that function is potentially another story, depending on the specifics of your program.

    The main idea you need to consider is that of "ownership" of the pointed-to data. When you pass that pointer, does the calling function have ownership of the data being passed in? i.e. is it in the only place that this data can be referenced from? Are you giving up ownership of the pointed-to-data, with no chance that the calling function is ever going to reference the data again? If so, then you must delete it.

    If the calling function might reference the data again, then you must not delete it.

    If there are other references to the data through various data structures, then it's not safe to delete this data unless you have some discipline in place in your code to ensure that you will never reference the data again from those places. This is hard to do, and is the source of many programming bugs.

    C++ tr1's shared_ptr<> is a smart pointer that helps in these kinds of situations - it manages this ownership concept by keeping a reference count that tracks the number of references to the data. If the reference count is 1, then there is 1 clear owner. If the reference count is larger than 1, then ownership is shared. If the reference count is 0, then there are no more references to the data, and shared_ptr<> will delete it when the shared_ptr<> destructor is called.