on 18 Jul 2003 14:52:47 -0400,
hi all,
i am pretty new to c++. i have this problem for which i am unable to
think a solution. i don't understand how to pass a vector refernce
back to the callin function. And how this reference will be handled by
the calling function ? Can any one in the group point me to the
correct solution for it ? Any code snippets will be of great help.
A little more information on what you're trying to do
(syntactically-valid, compileable code snippers for instance) would help
My guess (and that's all it is) is that you're probably trying to
return a reference to a locally created vector. Something like:
std::vector<int>& fubar()
{
std::vector<int> v;
// do stuff
return v;
}
In short - don't do this. It's always a bad idea, and invokes undefined
behaviour (since the vector your reference refers to will be destroyed
at the end of the function, so your reference will no longer refer to it).
Undefined behaviour is something you should avoid wherever possible,
even if you "know" that the current compiler/library implementation you
are using will "do what you want" - the next release may not do.
You can do something like:
std::vector<int>& foo( std::vector<int>& v )
{
// do stuff...
return v;
}
And construct the vector before you call the function. Again, depending
on what you're trying to achieve, it might be a more elegant solution to
pass an output iterator of some sort to your function, thus:
template<typename OutputIterator>
OutputIterator bar( OutputIterator out )
{
// do stuff - "store" your results by writing
*out++ = some_value;
// ...
return out;
}
And you caller looks something like:
std::vector<int> v;
bar( std::back_inserter( v ) );
Of course, your called might one day want to use (e.g.) a deque as the
container, so the caller can change to:
std::deque<int> v;
bar( std::back_inserter( v ) );
and leave your function unchanged.
Regards,
Andy S