I’m a java programmer switching over to C++. I have a list of data in a class. I want to return the contents of a list stored in a class variable and then generate a new list and store it in the class variable so I can start adding new data to the empty list. I think I know how to do it, but I want to double check since I’m new to references and c++ memory management and don’t want a stupid memory leak later. (note, I can’t copy my actual code easily so I’m just rewriting it, forgive me if I mistype anything).
I believe the correct syntax would be something like this:
//mylist is typedef of a list type
mylist& temporaryList=classList;
classList=myList();
return classList;
Is this syntax correct? Also, will I have to worry about freeing either the returned variable or the classList variable at any time or will RIAA take care of it all for me?
Sorry for asking such an easy question, but thank you for confirming my assumptions.
As @chris points out you have a problem in that you are using a reference, references have the nice feature that they alias the actual object at little to no cost, but in your case it means that when you reset the member list you are resetting the only list in your program.
The trivial naïve fix to your code is, as @chris also points out, to copy the list and then reset the original:
Now, the problem with this approach is that you are incurring the cost of copying when you know that the original list is going to be destroyed immediately. You can avoid that cost by using the copy-and-swap idiom(*):
mylist getAndClear() {
mylist tmp; // empty
swap( tmp, classList ); // swap contents, now classList is empty
// tmp holds the data
return tmp;
}
This is assuming that
mylistis astd::list. If it is not, make sure that you implementswap(or in C++11 move constructors, that will enable an efficientstd::swap).(*) While this may not seem a direct application of the copy-and-swap idiom, it actually is, where the modification to be applied is clearing the list. Perform a copy and apply the change over the copy (in this case the copy is avoided, as the change is emptying it), then swap the contents once the operation has completed successfully.