M
ma740988
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, 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. This
means the location of the allocated memory has been lost. If my
assessment is correct. I'm surpised the compiler (.NET) allowed me to
reseat ( right terminology ? ) the reference? Even more suprising is I
got the right answer ( 99 ).
I would think
const std::vector<bar>& f = run_it();
would be more prudent and it's now f's responsibility to clean up.
Thanks for the clarification..
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, 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. This
means the location of the allocated memory has been lost. If my
assessment is correct. I'm surpised the compiler (.NET) allowed me to
reseat ( right terminology ? ) the reference? Even more suprising is I
got the right answer ( 99 ).
I would think
const std::vector<bar>& f = run_it();
would be more prudent and it's now f's responsibility to clean up.
Thanks for the clarification..