chris mentions using a member function to reset or clear the object like this:
mylist tmp = classList;
classList.clear();
return tmp;
But you can usually do even better by avoiding the copy in the first place.
mylist tmp;
std::swap(tmp,classList);
return tmp;
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?
You don't need to delete
resources unless you new
them somewhere. And if you do use new
then you should also use smart pointers so you still won't have to delete
anything.
One of the most important things to understand about C++ coming from Java is that C++ objects are value-like objects by default. That is:
class A {
bool bar_called;
public:
A() : bar_called(false) {}
void bar() { bar_called = true; }
bool has_bar_been_called_on_this_object() { return bar_called; }
};
void foo(A a) {
a.bar();
}
int main() {
A a;
foo(a);
std::cout << a.has_bar_been_called_on_this_object() << '\n';
}
The output will indicate that bar has not been called on a
. Java uses, but tries to hide, pointers. So once you figure out pointers in C++ things should make more sense to you, and then you will be able figure out how to not use pointers.
Object o = new Object(); // Java hides the fact that o is a pointer to an Object, but fails to hide the consequences
Object b = o; // b is a pointer to an object, the same Object o points to.
// Equivalent C++
Object *o = new Object();
Object *b = o;
Judging from the C++ code you presented, in Java you'd do what your asking about something like this:
mylist tmp = classList;
classList = new mylist();
return tmp;
The equivalent in C++ would be:
mylist *tmp = classList; // classList is a pointer to a new'd up list.
classList = new mylist();
return tmp;
However that's not idomatic C++. In C++ you generally don't want to use pointers, and if you do you want to use smart pointers
std::shared_ptr<mylist> tmp = classList; // classList is a std::shared_ptr<mylist>
classList = std::make_shared<mylist>();
return tmp;
or
std::unique_ptr<mylist> tmp = std::move(classList); // classList is a unique_ptr
classList = std::unique_ptr<mylist>(new mylist()); // careful here, don't go calling a bunch of functions inside the mylist initializer, it's dangerous for reason beyond the scope of this post
return tmp;
But the C++ way is really to avoid pointers altogether.
mylist tmp; // classList is not a pointer at all
std::swap(tmp,classList); // the values of classList and tmp are swapped
return tmp; // tmp is returned by value, tmp has the same value as classList, but is not the same object, tmp and classList are objects, not pointers to objects as they are in Java or in the above C++ examples.