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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With