Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing new object to function c++

Tags:

c++

I just want to know if this is a bad practice to do.

for(int i=0;i<1000;i++)
    happyFunction(new Car());

The new car() object should live after calling it from happyFunction and later it should be destroyed . Now is that ok to do. I mean shouldn't I delete the memory allocated for that instance?

Example to make it more clear.

int i = 0;
for (i=0;i<1000;i++){
    new car();
}

Is this a good practice to do? Should I delete the memory allocation? I hope my question is clear. thank you.

like image 652
user1580731 Avatar asked Dec 26 '22 20:12

user1580731


1 Answers

happyFunction(new Car()); 

It's not bad practice in itsself (although almost certainly is wrong), the memory could be deleted inside the function. But that would be confusing so it's really not the best idea.

Also although it's safe with one parameter, if it was like this

happyFunction(new Car(), new Thing()); 

And one of the news threw an exception after the other new executed, the would be no way to free the memory so it's not safe.

You always have to free memory yourself in c++ so your second example leads to a big memory leak. There are classes such as unique_ptr and shared_ptr to help you manage it without having to write a delete yourself, you can find any number of tutorials online about them

like image 123
jcoder Avatar answered Jan 09 '23 02:01

jcoder