I had to implement a function that looked like this:
MyList * sum (MyList * l1, MyList * l2) {
MyList * newlist = new MyList();
//Adds two objects and place the result in a third new list
return newlist;
}
The function took two lists and placed the sum of each object into a new list. The MyList
class had nodes with pointers to the next
variable and the objects inside the list were user defined.
And that got me thinking - how should I deal with the dynamic allocation of memory from the objects and the list itself? Since I had to create memory for each of the objects of the new list.
Is there any way to place the values of the sum of objects in the new list without having to rely on dynamic allocation? Maybe by doing something like this:
Object result(node1->content + node2->content);
Node->content = &result; // will this object be erased when the function ends?
instead of this:
Node->content = new Object(node1->content + node2->content);
How should I deal with the lifetime of the new list created inside of the function in relation to the variable that will hold the memory after the function ends? Can I do something like this when returning the new list?
MyList & sum (MyList * l1, MyList * l2) {
//Create variable without allocating memory and return it's reference
}
In short, my main doubt is how to deal with the lifetime of an object that is created inside a function and will be held by other object.
std::shared_ptr
/std::unique_ptr
? – Hypercatalecticstd::list
. Thestd::list
automagically manages memory for you. – Lessielessing