Re: reference to a vector
ma740988 wrote:
I'm perusing source that quite frankly looks like a disaster in the
making. This is a case though where return by reference gets muddled
with my understand based on readings.
struct bar {
double variable;
void init() { memset ( this, 0, sizeof ( bar ) ); }
bar() { init(); }
bool operator <( bar & f ) const
{ return ( variable > f.variable ) ; }
};
std::vector< bar >& run_it ()
{
std::vector< bar > *ptr_f = new std::vector<bar >;
bar f;
f.variable = 99.;
ptr_f->push_back ( f );
return ( *ptr_f );
}
// later
int main()
{
std::vector<bar > f = run_it();
std::cout << f.size() << std::endl;
std::cout << f[ 0 ].variable << std::endl;
}
For starters, the memset seems to make an assumption that bar is a pod
type and it's not,
Agreed. It's horrible, and quite possibly UB.
but that aside my question is this:
The vector allocated in run_it is returned by reference to the local
variable f. I think though it's safe to state that the reference (i.e
temporary returned variable) has been reseated and copied to f.
No, ptr_f is a pointer to memory allocated from the free store. The
memory doesn't go away when run_it() exits, and run_it returns a
reference to the vector allocated on the free store. The problem is
that the memory leaks -- there's no way to delete the new'ed vector.