user361633
user361633

Reputation: 203

Operator New in function call

void F(A* a)
{
    delete a; 
};

F(new A());

Will the delete operator release the allocated memory or i must create and delete the object like this:

F(A* a) {} 

A a = new A();
F(a);
delete a;

Upvotes: 0

Views: 82

Answers (1)

alexrider
alexrider

Reputation: 4463

Yes it will free memory, but it is preferred to use smart pointers such as std::shared_ptr or boost::shared_ptr prior to C++11 instead. Also in your example it is better to set freed pointer to NULL to avoid double deallocation to avoiding dangling pointer errors.

void F(A*& a)
{
    delete a; 
    a = NULL;
};

You will not be able to call it as F(new A()); thru and will require to pass reference to pointer holding variable. Like in 2nd variant. There should be A* a = new A(); there thru, to indicate that a is a pointer.

Upvotes: 1

Related Questions