A little advice Returning Vectors Please

I am having trouble remembering how to return vectors back and forth between classes. I seem to remember that it is best to pass as reference parameters. I am having trouble with returning a vector to a parent class that was created in the child.

I am having trouble remembering how to return vectors back and forth between classes. I seem to remember that it is best to pass as reference parameters. I am having trouble with returning a vector to a parent class that was created in the child.

Here is my code concerning the vectors. assume that i have all the includes. and the rest of my code runs.

1
2
3
4
5
6
class parser
public:
vector<string>& parser(string input, string *del, int l);

private:
vector<string> returnValue;


1
2
3
4
5
6

vector<string>& parser(string input, string *del, int l)
{
dostuff with created vector
return returnValue;
}


so i was wondering 2 things first if i am passing by reference correctly? and second if i am defining my functions properly. the string *del is a pointer to a string array.
I am having trouble with returning a vector to a parent class that was created in the child.


If you create an object inside a function on the stack (i.e. you don't do it with new ), that object is destroyed when the function ends.

If you are trying to return a reference to it, you've got a problem, as the object ceases to exist as soon as the function ends.

Last edited on
i was kinda seeing that already. so what would solution be? pass around copies of a vector? the function has to create and destroy a new vector every time the function is called.

i tried to use an array but the size of the given array is determined by the input of the user and the actions of the function itself. the size cannot be predefined.
Don't create the vector where it will be destroyed while you still need it. Create it once at as high a level as you need to, and then pass it around by reference.

Like this, for example;

1
2
3
vector<string> object01; // create object01
somefunction (object01&);  // somefunction fiddles around with the object
// object sitll exists here, after the function has ended 

Thankyou Moschops. You are of great help. I dont know if it will completely work until i code it out but i believe that this solves my problem. Thankyou much

amaac
-Solved.
Topic archived. No new replies allowed.