user1112008
user1112008

Reputation: 442

Removing object inside function

Which code is good(if it is good)

void DeleteObject(Object* obj)
{
    delete obj;
}

or

void DeleteObject(Object** obj)  
{  
    delete *obj;  
}  

int main()  
{  
    Object *obj = new Object();  
    DeleteObject(&obj); or DeleteObject(obj);  
}  

In fact DeleteObject function is not so short(it deletes objects fields).

Upvotes: 0

Views: 1149

Answers (4)

pmr
pmr

Reputation: 59841

You say: "The function deletes object fields" which only means that something much more horrible is going on here. A class should be responsible for managing its own resources (sub-objects) in its destructor and constructors. If managing some sub-objects through the outside is required provide a public API to manage them. In any way, don't use raw-pointers to manage life-time, but use a smart-pointer (e.g. std::shared_ptr). There are of course some edge cases, but given that you are asking a question like this I don't think you have one on your hands.

Upvotes: 1

bjhend
bjhend

Reputation: 1713

I also recommend to use a smart pointer as suggested by @nightcracker, but if you really don't want that I recommend a reference to the pointer:

void DeleteObject(Object* &obj)
{
    delete obj;
    obj = NULL;
}

This ensures that the original pointer is set to null, so, you cannot accidentally access the object any more and a reference is safer than pointer to pointer.

Upvotes: 1

Ed Heal
Ed Heal

Reputation: 60047

In my opinion neither.

The person creating the object should be responsible for the object and thus delete it.

So my answer is that main should do the delete.

Upvotes: 6

orlp
orlp

Reputation: 118016

This is good:

#include <memory>

int main(int argc, char **argv) {  
    std::auto_ptr<Object> ptr = new Object();
}

Upvotes: 7

Related Questions