Search This Blog

Wednesday, June 10, 2009

Return From Value, Reference, And Pointer

//Need to explain more with Compiler Optimization with RETURN BY VALUE~
//p.732, p358, C++ Primer

class
LargeObject {
};


LargeObject return_by_value()
{

LargeObject lb;
return
lb; // make a copy of large object, then return it, might be slow
}

LargeObject& return_same_reference_from_parameter(LargeObject& lb)
{

//do something with lb,
return lb; //ok

}

LargeObject& return_by_local_reference_is_bad()
{

LargeObject lb;
return
lb; //oops, run time error, lb is destroyed after return
//compiler will warn!

}

LargeObject& return_from_heap_but_someone_has_to_free_it()
{

LargeObject *lb = new LargeObject();

return
*lb; // ok, BUT who is responsible to free the memory?
}

LargeObject* return_from_heap_but_someone_has_to_free_too()
{


LargeObject *lb = new LargeObject();
return
lb;
}




No comments: