I'm currently learning how to manipulate objects with functions in C++, and so far I have come to the following point:
If your object is potentially large, don't make it a local variable, i.e. keep it in the heap to save time on copying.
Specifically, I'm interested in a scenario where we are using a function that creates an object which did not exist before. I have put together the following small example to showcase what to do if you have a function:
#include <iostream>
using namespace std;
struct obj {
int first;
int second;
};
void setFirstVersionA(int a, obj * s)
{
s->first = a;
}
obj * setFirstVersionB(int a)
{
//in Version B I am creating a new object in the function but have to run delete outside
obj * s = new obj();
s->first = a;
return s;
}
int main(int argc, const char** argv)
{
obj * myobj = new obj();
setFirstVersionA(2,myobj);
//now I have the new obj in *i
cout << myobj->first;
delete myobj;
//this is an alternative to passing a pointer directly:
//no need to re-declare the pointer as delete only erases the myobj data
myobj = setFirstVersionB(3);
//now I have the new obj in *i
cout << myobj->first;
delete myobj;
return 0;
}
As far as I can tell, both functions achieve the same result.
I like version A better because it does not separate the new and delete declarations, and makes me less prone of forgetting to delete the object once I'm done. But it's a return type void and I find the code less readable because I have to actually check what the function does (and in general it means reading some other file).
I like version B better because it returns "the thing" that I wanted to change. So I know immediately, this function changes that guy (in this case the obj s). But it separates, new and delete. Which honestly, I find less terrible than having a series of void functions in my code and not seeing immediately what they do. Also, a lot has been written here about not returning pointers to local variables, but in variant B, though the object is created within a function, it is not a local variable (as it sits in the heap). Right?
Is there a better way to do it? Also, a "function creating an object which did not exist before" sounds a lot like a constructor. :) Should I be perhaps creating a class with a constructor for each of my objects?
Thanks for your advice!
obj *from the first function, if it is a question of readability for you.