hey, I got a question regarding functions returning a linked list. Here's the data structure of my linked list (just in case it deviates from the standard way of doing it)
template <class T> class Link
{
private:
unsigned int size;
Link<T> *nextRow;
Cell<T> *firstCell;
public:
Link();
~Link();
//functions
};
So each Link only consists of it's size, a pointer to the next link, and a pointer to the link's first cell, here is what the problem is I believe. If I have a function that returns say a Link<std::string>, naturally it only returns the Link element (as far as I can tell). I get an access violation if I do something along the lines of this:
Link<std::string> filled;
//fill filled with data
Link<std::string> link = TransferLink(filled);
//other file
template <class T> Link<T> Link<T>::TransferLink(Link<T> start)
{
Link<T> temp = start;
return temp;
}
Please note I do have '=' overloaded for Link, but I used this to isolate the problem of transferring the data between functions. What I think happens is c++ makes a temporary variable holding the value of "temp" calls the destructor on the actual variable "temp" and then sends the temporary variable to the "=" assignment. This would explain the access violation since calling the destructor on "temp" would destroy all of the cells in it, but it wouldn't update the size or the pointers of the temporary variable. That's just my thought on what happens. I have gotten it to work by doing the following, but it's really annoying to implement for larger functions:
template <class T> Link<T> Link<T>::TransferLink(Link<T> start)
{
Link<T> *temp = new Link<T>();
(*temp) = testMatrix[end];
return (*temp); //no destructor is called because of the 'new' operator
}
and then doing
Link<std::string> link = TransferLink(filled);
but this causes memory leaks obviously since my "=" makes new cells with the values of the right side parameter and then "temp" is never destroyed. So I made this:
template <class T> Link<T>& Link<T>::TransferLink(Link<T> start)
{
Link<T> *temp = new Link<T>();
(*temp) = testMatrix[end];
return (*temp); //no destructor is called because of the 'new' operator
}
and then doing
Link<std::string> link |= TransferLink(filled);
with "|=" being another overloaded operator the mimics the effects of "=" except that it destroys the variable on the right side.
So here's my question finally, I guess, is there any other way to transfer linked lists between functions than what I have done? This is fairly annoying to do and I've made a function list that mimics those of a vector because that's what I was using previously for all my functions. But when I needed to make the switch I wanted to make the transition fairly painless, and this is being a pain.
Thanks!
~J